code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
"""simple docstring""" from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCamelCase_ : """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : Collection[float] | None = None ) -> None: if components is None: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = list(UpperCAmelCase__ ) def __len__( self : List[str] ) -> int: return len(self.__components ) def __str__( self : List[str] ) -> str: return "(" + ",".join(map(UpperCAmelCase__ , self.__components ) ) + ")" def __add__( self : Optional[int] , UpperCAmelCase__ : Vector ) -> Vector: __SCREAMING_SNAKE_CASE = len(self ) if size == len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [self.__components[i] + other.component(UpperCAmelCase__ ) for i in range(UpperCAmelCase__ )] return Vector(UpperCAmelCase__ ) else: raise Exception("must have the same size" ) def __sub__( self : Optional[int] , UpperCAmelCase__ : Vector ) -> Vector: __SCREAMING_SNAKE_CASE = len(self ) if size == len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [self.__components[i] - other.component(UpperCAmelCase__ ) for i in range(UpperCAmelCase__ )] return Vector(UpperCAmelCase__ ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self : Union[str, Any] , UpperCAmelCase__ : float ) -> Vector: ... @overload def __mul__( self : int , UpperCAmelCase__ : Vector ) -> float: ... def __mul__( self : Optional[int] , UpperCAmelCase__ : float | Vector ) -> float | Vector: if isinstance(UpperCAmelCase__ , (float, int) ): __SCREAMING_SNAKE_CASE = [c * other for c in self.__components] return Vector(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and len(self ) == len(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = len(self ) __SCREAMING_SNAKE_CASE = [self.__components[i] * other.component(UpperCAmelCase__ ) for i in range(UpperCAmelCase__ )] return sum(UpperCAmelCase__ ) else: # error case raise Exception("invalid operand!" ) def UpperCAmelCase_ ( self : List[Any] ) -> Vector: return Vector(self.__components ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : int ) -> float: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : float ) -> None: assert -len(self.__components ) <= pos < len(self.__components ) __SCREAMING_SNAKE_CASE = value def UpperCAmelCase_ ( self : int ) -> float: if len(self.__components ) == 0: raise Exception("Vector is empty" ) __SCREAMING_SNAKE_CASE = [c**2 for c in self.__components] return math.sqrt(sum(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Vector , UpperCAmelCase__ : bool = False ) -> float: __SCREAMING_SNAKE_CASE = self * other __SCREAMING_SNAKE_CASE = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) return Vector([0] * dimension ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , lowerCAmelCase_ )) __SCREAMING_SNAKE_CASE = [0] * dimension __SCREAMING_SNAKE_CASE = 1 return Vector(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , (int, float) )) ) return x * scalar + y def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' random.seed(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] return Vector(lowerCAmelCase_ ) class UpperCamelCase_ : """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : list[list[float]] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> None: __SCREAMING_SNAKE_CASE = matrix __SCREAMING_SNAKE_CASE = w __SCREAMING_SNAKE_CASE = h def __str__( self : str ) -> str: __SCREAMING_SNAKE_CASE = "" 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 : Optional[Any] , UpperCAmelCase__ : Matrix ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __SCREAMING_SNAKE_CASE = [] for i in range(self.__height ): __SCREAMING_SNAKE_CASE = [ self.__matrix[i][j] + other.component(UpperCAmelCase__ , UpperCAmelCase__ ) for j in range(self.__width ) ] matrix.append(UpperCAmelCase__ ) return Matrix(UpperCAmelCase__ , self.__width , self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self : Dict , UpperCAmelCase__ : Matrix ) -> Matrix: if self.__width == other.width() and self.__height == other.height(): __SCREAMING_SNAKE_CASE = [] for i in range(self.__height ): __SCREAMING_SNAKE_CASE = [ self.__matrix[i][j] - other.component(UpperCAmelCase__ , UpperCAmelCase__ ) for j in range(self.__width ) ] matrix.append(UpperCAmelCase__ ) return Matrix(UpperCAmelCase__ , self.__width , self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self : Optional[int] , UpperCAmelCase__ : float ) -> Matrix: ... @overload def __mul__( self : Optional[int] , UpperCAmelCase__ : Vector ) -> Vector: ... def __mul__( self : List[str] , UpperCAmelCase__ : float | Vector ) -> Vector | Matrix: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): # matrix-vector if len(UpperCAmelCase__ ) == self.__width: __SCREAMING_SNAKE_CASE = zero_vector(self.__height ) for i in range(self.__height ): __SCREAMING_SNAKE_CASE = [ self.__matrix[i][j] * other.component(UpperCAmelCase__ ) for j in range(self.__width ) ] ans.change_component(UpperCAmelCase__ , sum(UpperCAmelCase__ ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(UpperCAmelCase__ , (int, float) ): # matrix-scalar __SCREAMING_SNAKE_CASE = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(UpperCAmelCase__ , self.__width , self.__height ) return None def UpperCAmelCase_ ( self : List[str] ) -> int: return self.__height def UpperCAmelCase_ ( self : List[Any] ) -> int: return self.__width def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float: if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : float ) -> None: if 0 <= x < self.__height and 0 <= y < self.__width: __SCREAMING_SNAKE_CASE = value else: raise Exception("change_component: indices out of bounds" ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float: if self.__height != self.__width: raise Exception("Matrix is not square" ) __SCREAMING_SNAKE_CASE = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(UpperCAmelCase__ ) ): __SCREAMING_SNAKE_CASE = minor[i][:y] + minor[i][y + 1 :] return Matrix(UpperCAmelCase__ , self.__width - 1 , self.__height - 1 ).determinant() def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> float: 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(UpperCAmelCase__ , UpperCAmelCase__ ) else: raise Exception("Indices out of bounds" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> float: 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: __SCREAMING_SNAKE_CASE = [ self.__matrix[0][y] * self.cofactor(0 , UpperCAmelCase__ ) for y in range(self.__width ) ] return sum(UpperCAmelCase__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [[0] * n for _ in range(lowerCAmelCase_ )] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' random.seed(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [ [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] for _ in range(lowerCAmelCase_ ) ] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase_ ( self : Dict ) -> Optional[int]: __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(UpperCAmelCase__ ) return image @property def UpperCAmelCase_ ( self : List[str] ) -> List[str]: torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = UNetaDConditionModel( block_out_channels=(3_2, 3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=7 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=3_2 , attention_head_dim=8 , use_linear_projection=UpperCAmelCase__ , only_cross_attention=(True, True, False) , num_class_embeds=1_0_0 , ) return model @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = AutoencoderKL( block_out_channels=[3_2, 3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) return model @property def UpperCAmelCase_ ( self : str ) -> List[str]: 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 , hidden_act="gelu" , projection_dim=5_1_2 , ) return CLIPTextModel(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> int: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.dummy_cond_unet_upscale __SCREAMING_SNAKE_CASE = DDPMScheduler() __SCREAMING_SNAKE_CASE = DDIMScheduler(prediction_type="v_prediction" ) __SCREAMING_SNAKE_CASE = self.dummy_vae __SCREAMING_SNAKE_CASE = self.dummy_text_encoder __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __SCREAMING_SNAKE_CASE = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(UpperCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # make sure here that pndm scheduler skips prk __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=3_5_0 , ) __SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) __SCREAMING_SNAKE_CASE = output.images __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , return_dict=UpperCAmelCase__ , )[0] __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = image_from_tuple[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) __SCREAMING_SNAKE_CASE = np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.dummy_cond_unet_upscale __SCREAMING_SNAKE_CASE = DDPMScheduler() __SCREAMING_SNAKE_CASE = DDIMScheduler(prediction_type="v_prediction" ) __SCREAMING_SNAKE_CASE = self.dummy_vae __SCREAMING_SNAKE_CASE = self.dummy_text_encoder __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __SCREAMING_SNAKE_CASE = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(UpperCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # make sure here that pndm scheduler skips prk __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=3_5_0 , ) __SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" __SCREAMING_SNAKE_CASE = sd_pipe( 2 * [prompt] , image=2 * [low_res_image] , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) __SCREAMING_SNAKE_CASE = output.images assert image.shape[0] == 2 __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_images_per_prompt=2 , guidance_scale=6.0 , noise_level=2_0 , num_inference_steps=2 , output_type="np" , ) __SCREAMING_SNAKE_CASE = output.images assert image.shape[0] == 2 @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.dummy_cond_unet_upscale __SCREAMING_SNAKE_CASE = DDPMScheduler() __SCREAMING_SNAKE_CASE = DDIMScheduler(prediction_type="v_prediction" ) __SCREAMING_SNAKE_CASE = self.dummy_vae __SCREAMING_SNAKE_CASE = self.dummy_text_encoder __SCREAMING_SNAKE_CASE = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __SCREAMING_SNAKE_CASE = self.dummy_image.cpu().permute(0 , 2 , 3 , 1 )[0] __SCREAMING_SNAKE_CASE = Image.fromarray(np.uinta(UpperCAmelCase__ ) ).convert("RGB" ).resize((6_4, 6_4) ) # put models in fp16, except vae as it overflows in fp16 __SCREAMING_SNAKE_CASE = unet.half() __SCREAMING_SNAKE_CASE = text_encoder.half() # make sure here that pndm scheduler skips prk __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline( unet=UpperCAmelCase__ , low_res_scheduler=UpperCAmelCase__ , scheduler=UpperCAmelCase__ , vae=UpperCAmelCase__ , text_encoder=UpperCAmelCase__ , tokenizer=UpperCAmelCase__ , max_noise_level=3_5_0 , ) __SCREAMING_SNAKE_CASE = sd_pipe.to(UpperCAmelCase__ ) sd_pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "A painting of a squirrel eating a burger" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = sd_pipe( [prompt] , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=2 , output_type="np" , ).images __SCREAMING_SNAKE_CASE = low_res_image.size[0] * 4 assert image.shape == (1, expected_height_width, expected_height_width, 3) @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple ) -> List[str]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __SCREAMING_SNAKE_CASE = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat.npy" ) __SCREAMING_SNAKE_CASE = "stabilityai/stable-diffusion-x4-upscaler" __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline.from_pretrained(UpperCAmelCase__ ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = "a cat sitting on a park bench" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type="np" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 1E-3 def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __SCREAMING_SNAKE_CASE = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale" "/upsampled_cat_fp16.npy" ) __SCREAMING_SNAKE_CASE = "stabilityai/stable-diffusion-x4-upscaler" __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline.from_pretrained( UpperCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing() __SCREAMING_SNAKE_CASE = "a cat sitting on a park bench" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , output_type="np" , ) __SCREAMING_SNAKE_CASE = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert np.abs(expected_image - image ).max() < 5E-1 def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __SCREAMING_SNAKE_CASE = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) __SCREAMING_SNAKE_CASE = "stabilityai/stable-diffusion-x4-upscaler" __SCREAMING_SNAKE_CASE = StableDiffusionUpscalePipeline.from_pretrained( UpperCAmelCase__ , torch_dtype=torch.floataa , ) pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __SCREAMING_SNAKE_CASE = "a cat sitting on a park bench" __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = pipe( prompt=UpperCAmelCase__ , image=UpperCAmelCase__ , generator=UpperCAmelCase__ , num_inference_steps=5 , output_type="np" , ) __SCREAMING_SNAKE_CASE = torch.cuda.max_memory_allocated() # make sure that less than 2.9 GB is allocated assert mem_bytes < 2.9 * 1_0**9
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "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] ) ) __SCREAMING_SNAKE_CASE = { "do_resize": True, "size": 2_0, "do_center_crop": True, "crop_size": 1_8, "do_normalize": True, "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073], "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711], } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , UpperCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , **UpperCAmelCase__ : Dict ) -> Optional[int]: return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : Optional[int] ) -> List[Any]: return BertTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , **UpperCAmelCase__ : Optional[int] ) -> Tuple: return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(UpperCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=UpperCAmelCase__ , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = AlignProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(UpperCAmelCase__ , return_tensors="np" ) __SCREAMING_SNAKE_CASE = processor(images=UpperCAmelCase__ , return_tensors="np" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , padding="max_length" , max_length=6_4 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase__ ): processor() def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = AlignProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "lower newer" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" from __future__ import annotations import inspect import unittest import numpy as np from transformers import ResNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFResNetForImageClassification, TFResNetModel from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[int] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any]=3 , UpperCAmelCase__ : Optional[int]=3_2 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : int=1_0 , UpperCAmelCase__ : Union[str, Any]=[1_0, 2_0, 3_0, 4_0] , UpperCAmelCase__ : List[Any]=[1, 1, 2, 1] , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : str="relu" , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Any=None , ) -> Dict: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embeddings_size __SCREAMING_SNAKE_CASE = hidden_sizes __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: return ResNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = TFResNetModel(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = TFResNetForImageClassification(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else () snake_case__ : Dict = ( {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification} if is_tf_available() else {} ) snake_case__ : Any = False snake_case__ : Tuple = False snake_case__ : int = False snake_case__ : Tuple = False snake_case__ : str = False def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = TFResNetModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> str: 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 UpperCAmelCase_ ( self : int ) -> Any: return @unittest.skip(reason="ResNet does not use inputs_embeds" ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="ResNet does not support input and output embeddings" ) def UpperCAmelCase_ ( self : Dict ) -> str: pass def UpperCAmelCase_ ( self : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> str: def check_hidden_states_output(UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase__ ) , expected_num_stages + 1 ) # ResNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __SCREAMING_SNAKE_CASE = layer_type __SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = TFResNetModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : Any ) -> Tuple: return ( AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: __SCREAMING_SNAKE_CASE = TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="tf" ) # forward pass __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = tf.TensorShape((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.constant([-11.1_069, -9.7_877, -8.3_777] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __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 = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if len(lowerCAmelCase_ ) <= 1: return [tuple(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = [] def generate(lowerCAmelCase_ , lowerCAmelCase_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , lowerCAmelCase_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = arr[k - 1], arr[i] else: # k is odd __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = arr[k - 1], arr[0] generate(k - 1 , lowerCAmelCase_ ) generate(len(lowerCAmelCase_ ) , lowerCAmelCase_ ) return res if __name__ == "__main__": a__ : List[Any] = input('''Enter numbers separated by a comma:\n''').strip() a__ : str = [int(item) for item in user_input.split(''',''')] print(heaps(arr))
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.test_utils import execute_subprocess_async def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("test" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate test command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.path.sep.join(__file__.split(os.path.sep )[:-2] + ["test_utils", "scripts", "test_script.py"] ) if args.config_file is None: __SCREAMING_SNAKE_CASE = script_name else: __SCREAMING_SNAKE_CASE = f"""--config_file={args.config_file} {script_name}""" __SCREAMING_SNAKE_CASE = ["accelerate-launch"] + test_args.split() __SCREAMING_SNAKE_CASE = execute_subprocess_async(lowerCAmelCase_ , env=os.environ.copy() ) if result.returncode == 0: print("Test is a success! You are ready for your distributed training!" ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() test_command(lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast a__ : Any = datasets.utils.logging.get_logger(__name__) @dataclass class UpperCamelCase_ ( datasets.BuilderConfig): """simple docstring""" snake_case__ : int = 10000 snake_case__ : Optional[List[str]] = None snake_case__ : Optional[datasets.Features] = None class UpperCamelCase_ ( datasets.ArrowBasedBuilder): """simple docstring""" snake_case__ : List[str] = ParquetConfig def UpperCAmelCase_ ( self : List[str] ) -> Dict: return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) __SCREAMING_SNAKE_CASE = dl_manager.download_and_extract(self.config.data_files ) if isinstance(UpperCAmelCase__ , (str, list, tuple) ): __SCREAMING_SNAKE_CASE = data_files if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE = [dl_manager.iter_files(UpperCAmelCase__ ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] __SCREAMING_SNAKE_CASE = [] for split_name, files in data_files.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __SCREAMING_SNAKE_CASE = [dl_manager.iter_files(UpperCAmelCase__ ) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(UpperCAmelCase__ ): with open(UpperCAmelCase__ , "rb" ) as f: __SCREAMING_SNAKE_CASE = datasets.Features.from_arrow_schema(pq.read_schema(UpperCAmelCase__ ) ) break splits.append(datasets.SplitGenerator(name=UpperCAmelCase__ , gen_kwargs={"files": files} ) ) return splits def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : pa.Table ) -> pa.Table: if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __SCREAMING_SNAKE_CASE = table_cast(UpperCAmelCase__ , self.info.features.arrow_schema ) return pa_table def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema ) != sorted(self.config.columns ): raise ValueError( F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'""" ) for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase__ ) ): with open(UpperCAmelCase__ , "rb" ) as f: __SCREAMING_SNAKE_CASE = pq.ParquetFile(UpperCAmelCase__ ) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size , columns=self.config.columns ) ): __SCREAMING_SNAKE_CASE = pa.Table.from_batches([record_batch] ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"""{file_idx}_{batch_idx}""", self._cast_table(UpperCAmelCase__ ) except ValueError as e: logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase__ )}: {e}""" ) raise
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" import logging from dataclasses import dataclass, field from pathlib import Path from typing import Optional, Union from .generation.configuration_utils import GenerationConfig from .training_args import TrainingArguments from .utils import add_start_docstrings a__ : Tuple = logging.getLogger(__name__) @dataclass @add_start_docstrings(TrainingArguments.__doc__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : bool = field(default=UpperCamelCase , metadata={"help": "Whether to use SortishSampler or not."}) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `max_length` value of the model configuration." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default " "to the `num_beams` value of the model configuration." ) } , ) snake_case__ : Optional[Union[str, Path, GenerationConfig]] = field( default=UpperCamelCase , metadata={ "help": "Model id, file path or url pointing to a GenerationConfig json file, to use during prediction." } , ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().to_dict() for k, v in d.items(): if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = v.to_dict() return d
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "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, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer a__ : int = logging.get_logger(__name__) a__ : Dict = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Any = { '''vocab_file''': { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt''' ), } } a__ : Any = { '''junnyu/roformer_chinese_small''': 1_5_3_6, '''junnyu/roformer_chinese_base''': 1_5_3_6, '''junnyu/roformer_chinese_char_small''': 5_1_2, '''junnyu/roformer_chinese_char_base''': 5_1_2, '''junnyu/roformer_small_discriminator''': 1_2_8, '''junnyu/roformer_small_generator''': 1_2_8, } a__ : str = { '''junnyu/roformer_chinese_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_base''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_small''': {'''do_lower_case''': True}, '''junnyu/roformer_chinese_char_base''': {'''do_lower_case''': True}, '''junnyu/roformer_small_discriminator''': {'''do_lower_case''': True}, '''junnyu/roformer_small_generator''': {'''do_lower_case''': True}, } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : int = PRETRAINED_INIT_CONFIGURATION snake_case__ : Optional[Any] = RoFormerTokenizer def __init__( self : str , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : str="[UNK]" , UpperCAmelCase__ : Union[str, Any]="[SEP]" , UpperCAmelCase__ : Dict="[PAD]" , UpperCAmelCase__ : str="[CLS]" , UpperCAmelCase__ : int="[MASK]" , UpperCAmelCase__ : Union[str, Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : int , ) -> str: super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase__ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase__ ) != strip_accents ): __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , pre_tok_state.pop("type" ) ) __SCREAMING_SNAKE_CASE = do_lower_case __SCREAMING_SNAKE_CASE = strip_accents __SCREAMING_SNAKE_CASE = pre_tok_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = do_lower_case def __getstate__( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.__dict__.copy() __SCREAMING_SNAKE_CASE = BertPreTokenizer() return state def __setstate__( self : str , UpperCAmelCase__ : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = d __SCREAMING_SNAKE_CASE = self.__dict__["_tokenizer"].get_vocab() __SCREAMING_SNAKE_CASE = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[int]=None ) -> List[str]: __SCREAMING_SNAKE_CASE = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : int=False , **UpperCAmelCase__ : Optional[Any] , ) -> int: __SCREAMING_SNAKE_CASE = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ )
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py a__ : str = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. a__ : List[Any] = direct_transformers_import(PATH_TO_TRANSFORMERS) a__ : Dict = transformers.models.auto.configuration_auto.CONFIG_MAPPING a__ : int = { # used to compute the property `self.chunk_length` '''EncodecConfig''': ['''overlap'''], # used as `self.bert_model = BertModel(config, ...)` '''DPRConfig''': True, # not used in modeling files, but it's an important information '''FSMTConfig''': ['''langs'''], # used internally in the configuration class file '''GPTNeoConfig''': ['''attention_types'''], # used internally in the configuration class file '''EsmConfig''': ['''is_folding_model'''], # used during training (despite we don't have training script for these models yet) '''Mask2FormerConfig''': ['''ignore_value'''], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) '''OneFormerConfig''': ['''ignore_value''', '''norm'''], # used during preprocessing and collation, see `collating_graphormer.py` '''GraphormerConfig''': ['''spatial_pos_max'''], # used internally in the configuration class file '''T5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally '''MT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], '''UMT5Config''': ['''feed_forward_proj''', '''tokenizer_class'''], # used internally in the configuration class file '''LongT5Config''': ['''feed_forward_proj'''], # used internally in the configuration class file '''SwitchTransformersConfig''': ['''feed_forward_proj'''], # having default values other than `1e-5` - we can't fix them without breaking '''BioGptConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''GLPNConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''SegformerConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''CvtConfig''': ['''layer_norm_eps'''], # having default values other than `1e-5` - we can't fix them without breaking '''PerceiverConfig''': ['''layer_norm_eps'''], # used internally to calculate the feature size '''InformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''TimeSeriesTransformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate the feature size '''AutoformerConfig''': ['''num_static_real_features''', '''num_time_features'''], # used internally to calculate `mlp_dim` '''SamVisionConfig''': ['''mlp_ratio'''], # For (head) training, but so far not implemented '''ClapAudioConfig''': ['''num_classes'''], # Not used, but providing useful information to users '''SpeechT5HifiGanConfig''': ['''sampling_rate'''], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { '''CLIPSegConfig''': True, '''DeformableDetrConfig''': True, '''DetaConfig''': True, '''DinatConfig''': True, '''DonutSwinConfig''': True, '''EfficientFormerConfig''': True, '''FSMTConfig''': True, '''JukeboxConfig''': True, '''LayoutLMv2Config''': True, '''MaskFormerSwinConfig''': True, '''MT5Config''': True, '''NatConfig''': True, '''OneFormerConfig''': True, '''PerceiverConfig''': True, '''RagConfig''': True, '''SpeechT5Config''': True, '''SwinConfig''': True, '''Swin2SRConfig''': True, '''Swinv2Config''': True, '''SwitchTransformersConfig''': True, '''TableTransformerConfig''': True, '''TapasConfig''': True, '''TransfoXLConfig''': True, '''UniSpeechConfig''': True, '''UniSpeechSatConfig''': True, '''WavLMConfig''': True, '''WhisperConfig''': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) '''JukeboxPriorConfig''': True, # TODO: @Younes (for `is_decoder`) '''Pix2StructTextConfig''': True, } ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f"""config.{attribute}""" in modeling_source or f"""getattr(config, \"{attribute}\"""" in modeling_source or f"""getattr(self.config, \"{attribute}\"""" in modeling_source ): __SCREAMING_SNAKE_CASE = True # Deal with multi-line cases elif ( re.search( Rf"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , lowerCAmelCase_ , ) is not None ): __SCREAMING_SNAKE_CASE = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: __SCREAMING_SNAKE_CASE = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files __SCREAMING_SNAKE_CASE = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] __SCREAMING_SNAKE_CASE = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed __SCREAMING_SNAKE_CASE = True if not attribute_used: __SCREAMING_SNAKE_CASE = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: __SCREAMING_SNAKE_CASE = True elif attribute in ["tie_word_embeddings"] and default_value is False: __SCREAMING_SNAKE_CASE = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: __SCREAMING_SNAKE_CASE = True elif attribute.endswith("_token_id" ): __SCREAMING_SNAKE_CASE = True # configuration class specific cases if not case_allowed: __SCREAMING_SNAKE_CASE = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) __SCREAMING_SNAKE_CASE = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = dict(inspect.signature(config_class.__init__ ).parameters ) __SCREAMING_SNAKE_CASE = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] __SCREAMING_SNAKE_CASE = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass __SCREAMING_SNAKE_CASE = {} if len(config_class.attribute_map ) > 0: __SCREAMING_SNAKE_CASE = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files __SCREAMING_SNAKE_CASE = inspect.getsourcefile(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = os.path.dirname(lowerCAmelCase_ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. __SCREAMING_SNAKE_CASE = [os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) for fn in os.listdir(lowerCAmelCase_ ) if fn.startswith("modeling_" )] # Get the source code strings __SCREAMING_SNAKE_CASE = [] for path in modeling_paths: if os.path.isfile(lowerCAmelCase_ ): with open(lowerCAmelCase_ ) as fp: modeling_sources.append(fp.read() ) __SCREAMING_SNAKE_CASE = [] for config_param, default_value in zip(lowerCAmelCase_ , lowerCAmelCase_ ): # `attributes` here is all the variant names for `config_param` __SCREAMING_SNAKE_CASE = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): unused_attributes.append(attributes[0] ) return sorted(lowerCAmelCase_ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) __SCREAMING_SNAKE_CASE = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda lowerCAmelCase_ : inspect.isclass(lowerCAmelCase_ ) and issubclass(lowerCAmelCase_ , lowerCAmelCase_ ) and inspect.getmodule(lowerCAmelCase_ ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: __SCREAMING_SNAKE_CASE = check_config_attributes_being_used(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = unused_attributes if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += f"""{name}: {attributes}\n""" raise ValueError(lowerCAmelCase_ ) if __name__ == "__main__": check_config_attributes()
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" @register_to_config def __init__( self : List[Any] , UpperCAmelCase__ : int = 7_6_8 , ) -> List[str]: super().__init__() __SCREAMING_SNAKE_CASE = nn.Parameter(torch.zeros(1 , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(1 , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[Union[str, torch.device]] = None , UpperCAmelCase__ : Optional[torch.dtype] = None , ) -> Tuple: __SCREAMING_SNAKE_CASE = nn.Parameter(self.mean.to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = nn.Parameter(self.std.to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) ) return self def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = (embeds - self.mean) * 1.0 / self.std return embeds def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict ) -> Tuple: __SCREAMING_SNAKE_CASE = (embeds * self.std) + self.mean return embeds
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" 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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" , return_dict=UpperCAmelCase__ ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("google/mt5-small" ) __SCREAMING_SNAKE_CASE = tokenizer("Hello there" , return_tensors="pt" ).input_ids __SCREAMING_SNAKE_CASE = tokenizer("Hi I am" , return_tensors="pt" ).input_ids __SCREAMING_SNAKE_CASE = model(input_ids.to(UpperCAmelCase__ ) , labels=labels.to(UpperCAmelCase__ ) ).loss __SCREAMING_SNAKE_CASE = -(labels.shape[-1] * loss.item()) __SCREAMING_SNAKE_CASE = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig a__ : Optional[Any] = { '''google/tapas-base-finetuned-sqa''': ( '''https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wtq''': ( '''https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json''' ), '''google/tapas-base-finetuned-wikisql-supervised''': ( '''https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json''' ), '''google/tapas-base-finetuned-tabfact''': ( '''https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "tapas" def __init__( self : Optional[int] , UpperCAmelCase__ : List[str]=3_0_5_2_2 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : List[Any]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : str="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Any=1_0_2_4 , UpperCAmelCase__ : str=[3, 2_5_6, 2_5_6, 2, 2_5_6, 2_5_6, 1_0] , UpperCAmelCase__ : Union[str, Any]=0.02 , UpperCAmelCase__ : Tuple=1E-12 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : Optional[Any]=10.0 , UpperCAmelCase__ : Optional[Any]=0 , UpperCAmelCase__ : Optional[int]=1.0 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Any=1.0 , UpperCAmelCase__ : List[Any]=False , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : str=1.0 , UpperCAmelCase__ : Optional[Any]=1.0 , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Optional[Any]="ratio" , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Dict=6_4 , UpperCAmelCase__ : int=3_2 , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : str=False , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Any=None , **UpperCAmelCase__ : List[Any] , ) -> List[str]: super().__init__(pad_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_sizes __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps # Fine-tuning task hyperparameters __SCREAMING_SNAKE_CASE = positive_label_weight __SCREAMING_SNAKE_CASE = num_aggregation_labels __SCREAMING_SNAKE_CASE = aggregation_loss_weight __SCREAMING_SNAKE_CASE = use_answer_as_supervision __SCREAMING_SNAKE_CASE = answer_loss_importance __SCREAMING_SNAKE_CASE = use_normalized_answer_loss __SCREAMING_SNAKE_CASE = huber_loss_delta __SCREAMING_SNAKE_CASE = temperature __SCREAMING_SNAKE_CASE = aggregation_temperature __SCREAMING_SNAKE_CASE = use_gumbel_for_cells __SCREAMING_SNAKE_CASE = use_gumbel_for_aggregation __SCREAMING_SNAKE_CASE = average_approximation_function __SCREAMING_SNAKE_CASE = cell_selection_preference __SCREAMING_SNAKE_CASE = answer_loss_cutoff __SCREAMING_SNAKE_CASE = max_num_rows __SCREAMING_SNAKE_CASE = max_num_columns __SCREAMING_SNAKE_CASE = average_logits_per_cell __SCREAMING_SNAKE_CASE = select_one_column __SCREAMING_SNAKE_CASE = allow_empty_column_selection __SCREAMING_SNAKE_CASE = init_cell_selection_weights_to_zero __SCREAMING_SNAKE_CASE = reset_position_index_per_cell __SCREAMING_SNAKE_CASE = disable_per_token_loss # Aggregation hyperparameters __SCREAMING_SNAKE_CASE = aggregation_labels __SCREAMING_SNAKE_CASE = no_aggregation_label_index if isinstance(self.aggregation_labels , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = {int(UpperCAmelCase__ ): v for k, v in aggregation_labels.items()}
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" from __future__ import annotations class UpperCamelCase_ : """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any]=None ) -> Dict: __SCREAMING_SNAKE_CASE = data __SCREAMING_SNAKE_CASE = None def __repr__( self : Optional[Any] ) -> int: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = self while temp: string_rep.append(F"""{temp.data}""" ) __SCREAMING_SNAKE_CASE = temp.next return "->".join(UpperCAmelCase__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not elements_list: raise Exception("The Elements List is empty" ) __SCREAMING_SNAKE_CASE = __SCREAMING_SNAKE_CASE = Node(elements_list[0] ) for i in range(1 , len(lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = Node(elements_list[i] ) __SCREAMING_SNAKE_CASE = current.next return head def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if head_node is not None and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): print_reverse(head_node.next ) print(head_node.data ) def UpperCAmelCase__ (): '''simple docstring''' from doctest import testmod testmod() __SCREAMING_SNAKE_CASE = make_linked_list([14, 52, 14, 12, 43] ) print("Linked List:" ) print(lowerCAmelCase_ ) print("Elements in Reverse:" ) print_reverse(lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[List[PIL.Image.Image], np.ndarray] snake_case__ : Optional[List[bool]] try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.26.0''')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('''>=''', '''0.0.12''') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : np.ndarray snake_case__ : List[bool] from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCamelCase_ ( metaclass=UpperCamelCase): """simple docstring""" snake_case__ : Any = ["torch", "torchsde"] def __init__( self : List[str] , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Dict ) -> Dict: requires_backends(self , ["torch", "torchsde"] ) @classmethod def UpperCAmelCase_ ( cls : Any , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Tuple: requires_backends(cls , ["torch", "torchsde"] ) @classmethod def UpperCAmelCase_ ( cls : Union[str, Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : Optional[int] ) -> Dict: requires_backends(cls , ["torch", "torchsde"] )
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" import argparse import json import re from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileNetVaConfig, MobileNetVaForImageClassification, MobileNetVaImageProcessor, load_tf_weights_in_mobilenet_va, ) from transformers.utils import logging logging.set_verbosity_info() a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = MobileNetVaConfig(layer_norm_eps=0.001 ) if "_quant" in model_name: raise ValueError("Quantized models are not supported." ) __SCREAMING_SNAKE_CASE = re.match(R"^mobilenet_v1_([^_]*)_([^_]*)$" , lowerCAmelCase_ ) if matches: __SCREAMING_SNAKE_CASE = float(matches[1] ) __SCREAMING_SNAKE_CASE = int(matches[2] ) # The TensorFlow version of MobileNetV1 predicts 1001 classes instead of # the usual 1000. The first class (index 0) is "background". __SCREAMING_SNAKE_CASE = 1001 __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ) + 1: v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = "background" __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = "http://images.cocodataset.org/val2017/000000039769.jpg" __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_mobilenet_va_config(lowerCAmelCase_ ) # Load 🤗 model __SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification(lowerCAmelCase_ ).eval() # Load weights from TensorFlow checkpoint load_tf_weights_in_mobilenet_va(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Check outputs on an image, prepared by MobileNetV1ImageProcessor __SCREAMING_SNAKE_CASE = MobileNetVaImageProcessor( crop_size={"width": config.image_size, "height": config.image_size} , size={"shortest_edge": config.image_size + 32} , ) __SCREAMING_SNAKE_CASE = image_processor(images=prepare_img() , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits assert logits.shape == (1, 1001) if model_name == "mobilenet_v1_1.0_224": __SCREAMING_SNAKE_CASE = torch.tensor([-4.1739, -1.1233, 3.1205] ) elif model_name == "mobilenet_v1_0.75_192": __SCREAMING_SNAKE_CASE = torch.tensor([-3.9440, -2.3141, -0.3333] ) else: __SCREAMING_SNAKE_CASE = None if expected_logits is not None: assert torch.allclose(logits[0, :3] , lowerCAmelCase_ , atol=1E-4 ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if push_to_hub: print("Pushing to the hub..." ) __SCREAMING_SNAKE_CASE = "google/" + model_name image_processor.push_to_hub(lowerCAmelCase_ ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''mobilenet_v1_1.0_224''', type=str, help='''Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.''', ) parser.add_argument( '''--checkpoint_path''', required=True, type=str, help='''Path to the original TensorFlow checkpoint (.ckpt file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', required=True, 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.''' ) a__ : int = parser.parse_args() convert_movilevit_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging a__ : Union[str, Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = ["pixel_values"] def __init__( self : Union[str, Any] , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : Union[int, float] = 1 / 2_5_5 , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 8 , **UpperCAmelCase__ : int , ) -> None: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = rescale_factor __SCREAMING_SNAKE_CASE = do_pad __SCREAMING_SNAKE_CASE = pad_size def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase__ : Dict ) -> np.ndarray: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Union[str, ChannelDimension]] = None ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_image_size(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (old_height // size + 1) * size - old_height __SCREAMING_SNAKE_CASE = (old_width // size + 1) * size - old_width return pad(UpperCAmelCase__ , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : ImageInput , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[float] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[Union[str, TensorType]] = None , UpperCAmelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ) -> Dict: __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor __SCREAMING_SNAKE_CASE = do_pad if do_pad is not None else self.do_pad __SCREAMING_SNAKE_CASE = pad_size if pad_size is not None else self.pad_size __SCREAMING_SNAKE_CASE = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_pad: __SCREAMING_SNAKE_CASE = [self.pad(UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" import string def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for key in range(len(string.ascii_uppercase ) ): __SCREAMING_SNAKE_CASE = "" for symbol in message: if symbol in string.ascii_uppercase: __SCREAMING_SNAKE_CASE = string.ascii_uppercase.find(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = num - key if num < 0: __SCREAMING_SNAKE_CASE = num + len(string.ascii_uppercase ) __SCREAMING_SNAKE_CASE = translated + string.ascii_uppercase[num] else: __SCREAMING_SNAKE_CASE = translated + symbol print(f"""Decryption using Key #{key}: {translated}""" ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = input("Encrypted message: " ) __SCREAMING_SNAKE_CASE = message.upper() decrypt(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch a__ : int = random.Random() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=1.0 , lowerCAmelCase_=None , lowerCAmelCase_=None ): '''simple docstring''' if rng is None: __SCREAMING_SNAKE_CASE = global_rng __SCREAMING_SNAKE_CASE = [] 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 UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int]=7 , UpperCAmelCase__ : Optional[Any]=4_0_0 , UpperCAmelCase__ : str=2_0_0_0 , UpperCAmelCase__ : Optional[int]=1_0 , UpperCAmelCase__ : List[str]=1_6_0 , UpperCAmelCase__ : str=8 , UpperCAmelCase__ : int=0.0 , UpperCAmelCase__ : int=4_0_0_0 , UpperCAmelCase__ : str=False , UpperCAmelCase__ : List[Any]=True , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = min_seq_length __SCREAMING_SNAKE_CASE = max_seq_length __SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) __SCREAMING_SNAKE_CASE = padding_value __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = return_attention_mask __SCREAMING_SNAKE_CASE = do_normalize __SCREAMING_SNAKE_CASE = feature_size __SCREAMING_SNAKE_CASE = chunk_length __SCREAMING_SNAKE_CASE = hop_length def UpperCAmelCase_ ( self : int ) -> str: return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Tuple=False ) -> List[str]: def _flatten(UpperCAmelCase__ : int ): return list(itertools.chain(*UpperCAmelCase__ ) ) if equal_length: __SCREAMING_SNAKE_CASE = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size __SCREAMING_SNAKE_CASE = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = WhisperFeatureExtractor if is_speech_available() else None def UpperCAmelCase_ ( self : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = WhisperFeatureExtractionTester(self ) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(UpperCAmelCase__ )[0] check_json_file_has_correct_format(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , "feat_extract.json" ) feat_extract_first.to_json_file(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() __SCREAMING_SNAKE_CASE = feat_extract_first.mel_filters __SCREAMING_SNAKE_CASE = feat_extract_second.mel_filters self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ ) ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: # Tests that all call wrap to encode_plus and batch_encode_plus __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(8_0_0 , 1_4_0_0 , 2_0_0 )] __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for speech_input in speech_inputs] # Test feature size __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , padding="max_length" , return_tensors="np" ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input __SCREAMING_SNAKE_CASE = feature_extractor(speech_inputs[0] , return_tensors="np" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] , return_tensors="np" ).input_features self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test batched __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)] __SCREAMING_SNAKE_CASE = np.asarray(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) # Test truncation required __SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(2_0_0 , (feature_extractor.n_samples + 5_0_0) , 2_0_0 )] __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for speech_input in speech_inputs] __SCREAMING_SNAKE_CASE = [x[: feature_extractor.n_samples] for x in speech_inputs] __SCREAMING_SNAKE_CASE = [np.asarray(UpperCAmelCase__ ) for speech_input in speech_inputs_truncated] __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ).input_features for enc_seq_a, enc_seq_a in zip(UpperCAmelCase__ , UpperCAmelCase__ ): self.assertTrue(np.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: import torch __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = np.random.rand(1_0_0 , 3_2 ).astype(np.floataa ) __SCREAMING_SNAKE_CASE = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"input_features": inputs}] , return_tensors="np" ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) __SCREAMING_SNAKE_CASE = feature_extractor.pad([{"input_features": inputs}] , return_tensors="pt" ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech __SCREAMING_SNAKE_CASE = ds.sort("id" ).select(range(UpperCAmelCase__ ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: # fmt: off __SCREAMING_SNAKE_CASE = torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on __SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) __SCREAMING_SNAKE_CASE = WhisperFeatureExtractor() __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="pt" ).input_features self.assertEqual(input_features.shape , (1, 8_0, 3_0_0_0) ) self.assertTrue(torch.allclose(input_features[0, 0, :3_0] , UpperCAmelCase__ , atol=1E-4 ) ) def UpperCAmelCase_ ( self : Tuple ) -> Any: __SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) __SCREAMING_SNAKE_CASE = self._load_datasamples(1 )[0] __SCREAMING_SNAKE_CASE = ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5 # Rescale to [0, 65535] to show issue __SCREAMING_SNAKE_CASE = feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=UpperCAmelCase__ )[0] self.assertTrue(np.all(np.mean(UpperCAmelCase__ ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(UpperCAmelCase__ ) - 1 ) < 1E-3 ) )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , 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 UpperCAmelCase_ ( self : List[Any] ) -> str: 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 UpperCAmelCase_ ( self : List[Any] ) -> List[str]: 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 UpperCAmelCase_ ( self : List[str] ) -> Tuple: 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 UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer a__ : int = logging.get_logger(__name__) a__ : Union[str, Any] = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} # See all BART models at https://huggingface.co/models?filter=bart a__ : List[str] = { '''vocab_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''', }, '''merges_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json''', '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json''', '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json''', '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json''', '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json''', '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json''', }, } a__ : str = { '''facebook/bart-base''': 1_0_2_4, '''facebook/bart-large''': 1_0_2_4, '''facebook/bart-large-mnli''': 1_0_2_4, '''facebook/bart-large-cnn''': 1_0_2_4, '''facebook/bart-large-xsum''': 1_0_2_4, '''yjernite/bart_eli5''': 1_0_2_4, } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = VOCAB_FILES_NAMES snake_case__ : str = PRETRAINED_VOCAB_FILES_MAP snake_case__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = ["input_ids", "attention_mask"] snake_case__ : Dict = BartTokenizer def __init__( self : str , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : str="replace" , UpperCAmelCase__ : Tuple="<s>" , UpperCAmelCase__ : Any="</s>" , UpperCAmelCase__ : Tuple="</s>" , UpperCAmelCase__ : Union[str, Any]="<s>" , UpperCAmelCase__ : Union[str, Any]="<unk>" , UpperCAmelCase__ : int="<pad>" , UpperCAmelCase__ : Dict="<mask>" , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Union[str, Any]=True , **UpperCAmelCase__ : int , ) -> Optional[int]: super().__init__( UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , errors=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , trim_offsets=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , UpperCAmelCase__ ) != add_prefix_space: __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , pre_tok_state.pop("type" ) ) __SCREAMING_SNAKE_CASE = add_prefix_space __SCREAMING_SNAKE_CASE = pre_tok_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` __SCREAMING_SNAKE_CASE = "post_processor" __SCREAMING_SNAKE_CASE = getattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ ) if tokenizer_component_instance: __SCREAMING_SNAKE_CASE = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __SCREAMING_SNAKE_CASE = tuple(state["sep"] ) if "cls" in state: __SCREAMING_SNAKE_CASE = tuple(state["cls"] ) __SCREAMING_SNAKE_CASE = False if state.get("add_prefix_space" , UpperCAmelCase__ ) != add_prefix_space: __SCREAMING_SNAKE_CASE = add_prefix_space __SCREAMING_SNAKE_CASE = True if state.get("trim_offsets" , UpperCAmelCase__ ) != trim_offsets: __SCREAMING_SNAKE_CASE = trim_offsets __SCREAMING_SNAKE_CASE = True if changes_to_apply: __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , state.pop("type" ) ) __SCREAMING_SNAKE_CASE = component_class(**UpperCAmelCase__ ) setattr(self.backend_tokenizer , UpperCAmelCase__ , UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : List[Any] ) -> str: if self._mask_token is None: if self.verbose: logger.error("Using mask_token, but it is not set yet." ) return None return str(self._mask_token ) @mask_token.setter def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else value __SCREAMING_SNAKE_CASE = value def UpperCAmelCase_ ( self : Dict , *UpperCAmelCase__ : List[str] , **UpperCAmelCase__ : List[Any] ) -> BatchEncoding: __SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , UpperCAmelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , *UpperCAmelCase__ : str , **UpperCAmelCase__ : int ) -> BatchEncoding: __SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , UpperCAmelCase__ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any]=None ) -> List[str]: __SCREAMING_SNAKE_CASE = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType a__ : Optional[List[str]] = None a__ : str = '''<''' if sys.byteorder == '''little''' else '''>''' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image a__ : Dict = [ np.dtype('''|b1'''), np.dtype('''|u1'''), np.dtype('''<u2'''), np.dtype('''>u2'''), np.dtype('''<i2'''), np.dtype('''>i2'''), np.dtype('''<u4'''), np.dtype('''>u4'''), np.dtype('''<i4'''), np.dtype('''>i4'''), np.dtype('''<f4'''), np.dtype('''>f4'''), np.dtype('''<f8'''), np.dtype('''>f8'''), ] @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : bool = True snake_case__ : Optional[str] = None # Automatically constructed snake_case__ : ClassVar[str] = "PIL.Image.Image" snake_case__ : ClassVar[Any] = pa.struct({"bytes": pa.binary(), "path": pa.string()}) snake_case__ : str = field(default="Image" , init=UpperCamelCase , repr=UpperCamelCase) def __call__( self : Union[str, Any] ) -> Union[str, Any]: return self.pa_type def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = np.array(UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": value, "bytes": None} elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return {"path": None, "bytes": value} elif isinstance(UpperCAmelCase__ , np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(UpperCAmelCase__ ) elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( F"""An image sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : dict , UpperCAmelCase__ : Any=None ) -> "PIL.Image.Image": if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Image(decode=True) instead." ) if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support decoding images, please install 'Pillow'." ) if token_per_repo_id is None: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(F"""An image should have one of 'path' or 'bytes' but both are None in {value}.""" ) else: if is_local_path(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = PIL.Image.open(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = path.split("::" )[-1] try: __SCREAMING_SNAKE_CASE = string_to_dict(UpperCAmelCase__ , config.HUB_DATASETS_URL )["repo_id"] __SCREAMING_SNAKE_CASE = token_per_repo_id.get(UpperCAmelCase__ ) except ValueError: __SCREAMING_SNAKE_CASE = None with xopen(UpperCAmelCase__ , "rb" , use_auth_token=UpperCAmelCase__ ) as f: __SCREAMING_SNAKE_CASE = BytesIO(f.read() ) __SCREAMING_SNAKE_CASE = PIL.Image.open(bytes_ ) else: __SCREAMING_SNAKE_CASE = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def UpperCAmelCase_ ( self : int ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return ( self if self.decode else { "bytes": Value("binary" ), "path": Value("string" ), } ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[pa.StringArray, pa.StructArray, pa.ListArray] ) -> pa.StructArray: if pa.types.is_string(storage.type ): __SCREAMING_SNAKE_CASE = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) __SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): __SCREAMING_SNAKE_CASE = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: __SCREAMING_SNAKE_CASE = storage.field("bytes" ) else: __SCREAMING_SNAKE_CASE = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: __SCREAMING_SNAKE_CASE = storage.field("path" ) else: __SCREAMING_SNAKE_CASE = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_list(storage.type ): __SCREAMING_SNAKE_CASE = pa.array( [encode_np_array(np.array(UpperCAmelCase__ ) )["bytes"] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) __SCREAMING_SNAKE_CASE = pa.array([None] * len(UpperCAmelCase__ ) , type=pa.string() ) __SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays( [bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : pa.StructArray ) -> pa.StructArray: @no_op_if_value_is_null def path_to_bytes(UpperCAmelCase__ : Dict ): with xopen(UpperCAmelCase__ , "rb" ) as f: __SCREAMING_SNAKE_CASE = f.read() return bytes_ __SCREAMING_SNAKE_CASE = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) __SCREAMING_SNAKE_CASE = pa.array( [os.path.basename(UpperCAmelCase__ ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) __SCREAMING_SNAKE_CASE = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(UpperCAmelCase__ , self.pa_type ) def UpperCAmelCase__ (): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() __SCREAMING_SNAKE_CASE = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = BytesIO() if image.format in list_image_compression_formats(): __SCREAMING_SNAKE_CASE = image.format else: __SCREAMING_SNAKE_CASE = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(lowerCAmelCase_ , format=lowerCAmelCase_ ) return buffer.getvalue() def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if hasattr(lowerCAmelCase_ , "filename" ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) __SCREAMING_SNAKE_CASE = array.dtype __SCREAMING_SNAKE_CASE = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER __SCREAMING_SNAKE_CASE = dtype.kind __SCREAMING_SNAKE_CASE = dtype.itemsize __SCREAMING_SNAKE_CASE = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: __SCREAMING_SNAKE_CASE = np.dtype("|u1" ) if dtype_kind not in ["u", "i"]: raise TypeError( f"""Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.""" ) if dtype is not dest_dtype: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: __SCREAMING_SNAKE_CASE = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: __SCREAMING_SNAKE_CASE = dtype_byteorder + dtype_kind + str(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.dtype(lowerCAmelCase_ ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f"""Downcasting array dtype {dtype} to {dest_dtype} to be compatible with 'Pillow'""" ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f"""Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}""" ) __SCREAMING_SNAKE_CASE = PIL.Image.fromarray(array.astype(lowerCAmelCase_ ) ) return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError("To support encoding images, please install 'Pillow'." ) if objs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = first_non_null_value(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowerCAmelCase_ , np.ndarray ): __SCREAMING_SNAKE_CASE = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): __SCREAMING_SNAKE_CASE = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] else: return objs else: return objs
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) a__ : Union[str, Any] = logging.getLogger() a__ : Tuple = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Dict ) -> Union[str, Any]: os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"source": "What is love ?", "target": "life"} __SCREAMING_SNAKE_CASE = {"train": 1_2, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: __SCREAMING_SNAKE_CASE = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(UpperCAmelCase__ , F"""{split}.{field}""" ) , "w" ) as f: f.write(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str = "pytorch" ) -> Tuple: __SCREAMING_SNAKE_CASE = self.get_auto_remove_tmp_dir() __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , "output" ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , "data" ) self._create_dummy_data(data_dir=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F""" --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ """.split() if gpus > 0: testargs.append(F"""--gpus={gpus}""" ) if is_apex_available(): testargs.append("--fp16" ) else: testargs.append("--gpus=0" ) testargs.append("--distributed_backend=ddp_cpu" ) testargs.append("--num_processes=2" ) __SCREAMING_SNAKE_CASE = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(UpperCAmelCase__ , env=self.get_env() ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , "metrics.json" ) with open(UpperCAmelCase__ ) as f: __SCREAMING_SNAKE_CASE = json.load(UpperCAmelCase__ ) return result @require_torch_gpu def UpperCAmelCase_ ( self : Any ) -> str: __SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_gpu @require_ray def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu @require_ray def UpperCAmelCase_ ( self : List[Any] ) -> int: __SCREAMING_SNAKE_CASE = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 )
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" __SCREAMING_SNAKE_CASE = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ).convert("RGB" ) __SCREAMING_SNAKE_CASE = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48145466, 0.4578275, 0.40821073) , (0.26862954, 0.26130258, 0.27577711) ), ] ) __SCREAMING_SNAKE_CASE = transform(lowerCAmelCase_ ).unsqueeze(0 ).to(lowerCAmelCase_ ) return image def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if "visual_encoder" in key: __SCREAMING_SNAKE_CASE = re.sub("visual_encoder*" , "vision_model.encoder" , lowerCAmelCase_ ) if "blocks" in key: __SCREAMING_SNAKE_CASE = re.sub(R"blocks" , "layers" , lowerCAmelCase_ ) if "attn" in key: __SCREAMING_SNAKE_CASE = re.sub(R"attn" , "self_attn" , lowerCAmelCase_ ) if "norm1" in key: __SCREAMING_SNAKE_CASE = re.sub(R"norm1" , "layer_norm1" , lowerCAmelCase_ ) if "norm2" in key: __SCREAMING_SNAKE_CASE = re.sub(R"norm2" , "layer_norm2" , lowerCAmelCase_ ) if "encoder.norm" in key: __SCREAMING_SNAKE_CASE = re.sub(R"encoder.norm" , "post_layernorm" , lowerCAmelCase_ ) if "encoder.patch_embed.proj" in key: __SCREAMING_SNAKE_CASE = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , lowerCAmelCase_ ) if "encoder.pos_embed" in key: __SCREAMING_SNAKE_CASE = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , lowerCAmelCase_ ) if "encoder.cls_token" in key: __SCREAMING_SNAKE_CASE = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , lowerCAmelCase_ ) if "self_attn" in key: __SCREAMING_SNAKE_CASE = re.sub(R"self_attn.proj" , "self_attn.projection" , lowerCAmelCase_ ) return key @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=None ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE = BlipConfig.from_pretrained(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = BlipConfig(projection_dim=512 , text_config={} , vision_config={} ) __SCREAMING_SNAKE_CASE = BlipForConditionalGeneration(lowerCAmelCase_ ).eval() __SCREAMING_SNAKE_CASE = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" __SCREAMING_SNAKE_CASE = blip_decoder(pretrained=lowerCAmelCase_ , image_size=384 , vit="base" ) __SCREAMING_SNAKE_CASE = pt_model.eval() __SCREAMING_SNAKE_CASE = pt_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE = modified_state_dict.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_key(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = value hf_model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 384 __SCREAMING_SNAKE_CASE = load_demo_image(image_size=lowerCAmelCase_ , device="cpu" ) __SCREAMING_SNAKE_CASE = BertTokenizer.from_pretrained("bert-base-uncased" ) __SCREAMING_SNAKE_CASE = tokenizer(["a picture of"] ).input_ids __SCREAMING_SNAKE_CASE = hf_model.generate(lowerCAmelCase_ , lowerCAmelCase_ ) assert out[0].tolist() == [3_0522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] __SCREAMING_SNAKE_CASE = hf_model.generate(lowerCAmelCase_ ) assert out[0].tolist() == [3_0522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(lowerCAmelCase_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' __SCREAMING_SNAKE_CASE = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) __SCREAMING_SNAKE_CASE = blip_vqa(pretrained=lowerCAmelCase_ , image_size=lowerCAmelCase_ , vit="base" ) vqa_model.eval() __SCREAMING_SNAKE_CASE = vqa_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE = modified_state_dict.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_key(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = BlipForQuestionAnswering(lowerCAmelCase_ ) hf_vqa_model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ["How many dogs are in this image?"] __SCREAMING_SNAKE_CASE = tokenizer(lowerCAmelCase_ , return_tensors="pt" ).input_ids __SCREAMING_SNAKE_CASE = hf_vqa_model.generate(lowerCAmelCase_ , lowerCAmelCase_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) __SCREAMING_SNAKE_CASE = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" __SCREAMING_SNAKE_CASE = blip_itm(pretrained=lowerCAmelCase_ , image_size=lowerCAmelCase_ , vit="base" ) itm_model.eval() __SCREAMING_SNAKE_CASE = itm_model.state_dict() for key in modified_state_dict.copy(): __SCREAMING_SNAKE_CASE = modified_state_dict.pop(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_key(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = value __SCREAMING_SNAKE_CASE = BlipForImageTextRetrieval(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ["A picture of a woman with a dog sitting in a beach"] __SCREAMING_SNAKE_CASE = tokenizer( lowerCAmelCase_ , return_tensors="pt" , padding="max_length" , truncation=lowerCAmelCase_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(lowerCAmelCase_ ) hf_itm_model.eval() __SCREAMING_SNAKE_CASE = hf_itm_model(lowerCAmelCase_ , lowerCAmelCase_ , use_itm_head=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = hf_itm_model(lowerCAmelCase_ , lowerCAmelCase_ , use_itm_head=lowerCAmelCase_ ) assert out[0].item() == 0.2110687494277954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.45698845386505127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') a__ : Dict = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" import os from glob import glob import imageio import torch import torchvision import wandb from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan from loaders import load_vqgan from PIL import Image from torch import nn from transformers import CLIPModel, CLIPTokenizerFast from utils import get_device, get_timestamp, show_pil class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : str = "cpu" , UpperCAmelCase__ : str = "openai/clip-vit-large-patch14" ) -> None: __SCREAMING_SNAKE_CASE = device __SCREAMING_SNAKE_CASE = CLIPTokenizerFast.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [0.48_145_466, 0.4_578_275, 0.40_821_073] __SCREAMING_SNAKE_CASE = [0.26_862_954, 0.26_130_258, 0.27_577_711] __SCREAMING_SNAKE_CASE = torchvision.transforms.Normalize(self.image_mean , self.image_std ) __SCREAMING_SNAKE_CASE = torchvision.transforms.Resize(2_2_4 ) __SCREAMING_SNAKE_CASE = torchvision.transforms.CenterCrop(2_2_4 ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : str ) -> Tuple: __SCREAMING_SNAKE_CASE = self.resize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.center_crop(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.normalize(UpperCAmelCase__ ) return images def __call__( self : Optional[int] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , **UpperCAmelCase__ : str ) -> Dict: __SCREAMING_SNAKE_CASE = self.tokenizer(text=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.preprocess_img(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {key: value.to(self.device ) for (key, value) in encoding.items()} return encoding class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Tuple=1_0 , UpperCAmelCase__ : List[Any]=0.01 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Optional[int]="image" , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : List[Any]=False , ) -> None: super().__init__() __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = device if device else get_device() if vqgan: __SCREAMING_SNAKE_CASE = vqgan else: __SCREAMING_SNAKE_CASE = load_vqgan(self.device , conf_path=UpperCAmelCase__ , ckpt_path=UpperCAmelCase__ ) self.vqgan.eval() if clip: __SCREAMING_SNAKE_CASE = clip else: __SCREAMING_SNAKE_CASE = CLIPModel.from_pretrained("openai/clip-vit-base-patch32" ) self.clip.to(self.device ) __SCREAMING_SNAKE_CASE = ProcessorGradientFlow(device=self.device ) __SCREAMING_SNAKE_CASE = iterations __SCREAMING_SNAKE_CASE = lr __SCREAMING_SNAKE_CASE = log __SCREAMING_SNAKE_CASE = make_grid __SCREAMING_SNAKE_CASE = return_val __SCREAMING_SNAKE_CASE = quantize __SCREAMING_SNAKE_CASE = self.vqgan.decoder.z_shape def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : Union[str, Any]=True ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = [] if output_path is None: __SCREAMING_SNAKE_CASE = "./animation.gif" if input_path is None: __SCREAMING_SNAKE_CASE = self.save_path __SCREAMING_SNAKE_CASE = sorted(glob(input_path + "/*" ) ) if not len(UpperCAmelCase__ ): raise ValueError( "No images found in save path, aborting (did you pass save_intermediate=True to the generate" " function?)" ) if len(UpperCAmelCase__ ) == 1: print("Only one image found in save path, (did you pass save_intermediate=True to the generate function?)" ) __SCREAMING_SNAKE_CASE = total_duration / len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [frame_duration] * len(UpperCAmelCase__ ) if extend_frames: __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = 3 for file_name in paths: if file_name.endswith(".png" ): images.append(imageio.imread(UpperCAmelCase__ ) ) imageio.mimsave(UpperCAmelCase__ , UpperCAmelCase__ , duration=UpperCAmelCase__ ) print(F"""gif saved to {output_path}""" ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Any=None ) -> Optional[Any]: if not (path or img): raise ValueError("Input either path or tensor" ) if img is not None: raise NotImplementedError __SCREAMING_SNAKE_CASE = preprocess(Image.open(UpperCAmelCase__ ) , target_image_size=2_5_6 ).to(self.device ) __SCREAMING_SNAKE_CASE = preprocess_vqgan(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE = self.vqgan.encode(UpperCAmelCase__ ) return z def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = self.latent.detach().requires_grad_() __SCREAMING_SNAKE_CASE = base_latent + transform_vector if self.quantize: __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE = self.vqgan.quantize(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = trans_latent return self.vqgan.decode(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Dict=None ) -> str: __SCREAMING_SNAKE_CASE = self.clip_preprocessor(text=UpperCAmelCase__ , images=UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.clip(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = clip_outputs.logits_per_image if weights is not None: __SCREAMING_SNAKE_CASE = similarity_logits * weights return similarity_logits.sum() def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self._get_clip_similarity(pos_prompts["prompts"] , UpperCAmelCase__ , weights=(1 / pos_prompts["weights"]) ) if neg_prompts: __SCREAMING_SNAKE_CASE = self._get_clip_similarity(neg_prompts["prompts"] , UpperCAmelCase__ , weights=neg_prompts["weights"] ) else: __SCREAMING_SNAKE_CASE = torch.tensor([1] , device=self.device ) __SCREAMING_SNAKE_CASE = -torch.log(UpperCAmelCase__ ) + torch.log(UpperCAmelCase__ ) return loss def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = torch.randn_like(self.latent , requires_grad=UpperCAmelCase__ , device=self.device ) __SCREAMING_SNAKE_CASE = torch.optim.Adam([vector] , lr=self.lr ) for i in range(self.iterations ): optim.zero_grad() __SCREAMING_SNAKE_CASE = self._add_vector(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = loop_post_process(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._get_CLIP_loss(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) print("CLIP loss" , UpperCAmelCase__ ) if self.log: wandb.log({"CLIP Loss": clip_loss} ) clip_loss.backward(retain_graph=UpperCAmelCase__ ) optim.step() if self.return_val == "image": yield custom_to_pil(transformed_img[0] ) else: yield vector def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict ) -> Optional[Any]: wandb.init(reinit=UpperCAmelCase__ , project="face-editor" ) wandb.config.update({"Positive Prompts": positive_prompts} ) wandb.config.update({"Negative Prompts": negative_prompts} ) wandb.config.update({"lr": self.lr, "iterations": self.iterations} ) if image_path: __SCREAMING_SNAKE_CASE = Image.open(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = image.resize((2_5_6, 2_5_6) ) wandb.log("Original Image" , wandb.Image(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] ) -> Tuple: if not prompts: return [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = [prompt.strip() for prompt in prompts.split("|" )] for prompt in prompts: if isinstance(UpperCAmelCase__ , (tuple, list) ): __SCREAMING_SNAKE_CASE = prompt[0] __SCREAMING_SNAKE_CASE = float(prompt[1] ) elif ":" in prompt: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = prompt.split(":" ) __SCREAMING_SNAKE_CASE = float(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = prompt __SCREAMING_SNAKE_CASE = 1.0 processed_prompts.append(UpperCAmelCase__ ) weights.append(UpperCAmelCase__ ) return { "prompts": processed_prompts, "weights": torch.tensor(UpperCAmelCase__ , device=self.device ), } def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : str=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : List[str]=False , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Dict=None , ) -> int: if image_path: __SCREAMING_SNAKE_CASE = self._get_latent(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = torch.randn(self.latent_dim , device=self.device ) if self.log: self._init_logging(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) assert pos_prompts, "You must provide at least one positive prompt." __SCREAMING_SNAKE_CASE = self.process_prompts(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.process_prompts(UpperCAmelCase__ ) if save_final and save_path is None: __SCREAMING_SNAKE_CASE = os.path.join("./outputs/" , "_".join(pos_prompts["prompts"] ) ) if not os.path.exists(UpperCAmelCase__ ): os.makedirs(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = save_path + "_" + get_timestamp() os.makedirs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = save_path __SCREAMING_SNAKE_CASE = self.vqgan.decode(self.latent )[0] if show_intermediate: print("Original Image" ) show_pil(custom_to_pil(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = loop_post_process(UpperCAmelCase__ ) for iter, transformed_img in enumerate(self._optimize_CLIP(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) ): if show_intermediate: show_pil(UpperCAmelCase__ ) if save_intermediate: transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}.png""" ) ) if self.log: wandb.log({"Image": wandb.Image(UpperCAmelCase__ )} ) if show_final: show_pil(UpperCAmelCase__ ) if save_final: transformed_img.save(os.path.join(self.save_path , F"""iter_{iter:03d}_final.png""" ) )
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __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 = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder a__ : Dict = '''__DUMMY_TRANSFORMERS_USER__''' a__ : Optional[int] = '''Dummy User''' a__ : Dict = '''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''' a__ : Optional[int] = '''https://hub-ci.huggingface.co''' a__ : str = CI_HUB_ENDPOINT + '''/datasets/{repo_id}/resolve/{revision}/{path}''' a__ : Union[str, Any] = CI_HUB_ENDPOINT + '''/{repo_id}/resolve/{revision}/{filename}''' a__ : Tuple = Path('''~/.huggingface/hub_ci_token''').expanduser() @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' monkeypatch.setattr( "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE" , lowerCAmelCase_ ) @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' monkeypatch.setattr("datasets.config.HF_ENDPOINT" , lowerCAmelCase_ ) monkeypatch.setattr("datasets.config.HUB_DATASETS_URL" , lowerCAmelCase_ ) @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token" , lowerCAmelCase_ ) @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' HfFolder.save_token(lowerCAmelCase_ ) yield HfFolder.delete_token() @pytest.fixture(scope="session" ) def UpperCAmelCase__ (): '''simple docstring''' return HfApi(endpoint=lowerCAmelCase_ ) @pytest.fixture(scope="session" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = HfFolder.get_token() HfFolder.save_token(lowerCAmelCase_ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(lowerCAmelCase_ ) @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def _cleanup_repo(lowerCAmelCase_ ): hf_api.delete_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" ) return _cleanup_repo @pytest.fixture def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' @contextmanager def _temporary_repo(lowerCAmelCase_ ): try: yield repo_id finally: cleanup_repo(lowerCAmelCase_ ) return _temporary_repo @pytest.fixture(scope="session" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""repo_txt_data-{int(time.time() * 10E3 )}""" __SCREAMING_SNAKE_CASE = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" , private=lowerCAmelCase_ ) hf_api.upload_file( token=lowerCAmelCase_ , path_or_fileobj=str(lowerCAmelCase_ ) , path_in_repo="data/text_data.txt" , repo_id=lowerCAmelCase_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="session" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""repo_zipped_txt_data-{int(time.time() * 10E3 )}""" __SCREAMING_SNAKE_CASE = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" , private=lowerCAmelCase_ ) hf_api.upload_file( token=lowerCAmelCase_ , path_or_fileobj=str(lowerCAmelCase_ ) , path_in_repo="data.zip" , repo_id=lowerCAmelCase_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="session" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = f"""repo_zipped_img_data-{int(time.time() * 10E3 )}""" __SCREAMING_SNAKE_CASE = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" , private=lowerCAmelCase_ ) hf_api.upload_file( token=lowerCAmelCase_ , path_or_fileobj=str(lowerCAmelCase_ ) , path_in_repo="data.zip" , repo_id=lowerCAmelCase_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(lowerCAmelCase_ , token=lowerCAmelCase_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return hf_private_dataset_repo_zipped_img_data_
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) while len(lowerCAmelCase_ ) != 1: __SCREAMING_SNAKE_CASE = [int(lowerCAmelCase_ ) for i in num_string] __SCREAMING_SNAKE_CASE = 1 for i in range(0 , len(lowerCAmelCase_ ) ): total *= numbers[i] __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) steps += 1 return steps def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) while len(lowerCAmelCase_ ) != 1: __SCREAMING_SNAKE_CASE = [int(lowerCAmelCase_ ) for i in num_string] __SCREAMING_SNAKE_CASE = 0 for i in range(0 , len(lowerCAmelCase_ ) ): total += numbers[i] __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ConsistencyModelPipeline snake_case__ : Optional[int] = UNCONDITIONAL_IMAGE_GENERATION_PARAMS snake_case__ : Dict = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt snake_case__ : Union[str, Any] = frozenset( [ "num_inference_steps", "generator", "latents", "output_type", "return_dict", "callback", "callback_steps", ]) @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained( "diffusers/consistency-models-test" , subfolder="test_unet" , ) return unet @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained( "diffusers/consistency-models-test" , subfolder="test_unet_class_cond" , ) return unet def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Any=False ) -> Dict: if class_cond: __SCREAMING_SNAKE_CASE = self.dummy_cond_unet else: __SCREAMING_SNAKE_CASE = self.dummy_uncond_unet # Default to CM multistep sampler __SCREAMING_SNAKE_CASE = CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.002 , sigma_max=80.0 , ) __SCREAMING_SNAKE_CASE = { "unet": unet, "scheduler": scheduler, } return components def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=0 ) -> Union[str, Any]: if str(UpperCAmelCase__ ).startswith("mps" ): __SCREAMING_SNAKE_CASE = torch.manual_seed(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "batch_size": 1, "num_inference_steps": None, "timesteps": [2_2, 0], "generator": generator, "output_type": "np", } return inputs def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components(class_cond=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.3_572, 0.6_273, 0.4_031, 0.3_961, 0.4_321, 0.5_730, 0.5_266, 0.4_780, 0.5_004] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components() __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = "cpu" # ensure determinism for the device-dependent torch.Generator __SCREAMING_SNAKE_CASE = self.get_dummy_components(class_cond=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = pipe.to(UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_dummy_inputs(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 3_2, 3_2, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.5_004, 0.5_004, 0.4_994, 0.5_008, 0.4_976, 0.5_018, 0.4_990, 0.4_982, 0.4_987] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @slow @require_torch_gpu class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Tuple=False , UpperCAmelCase__ : int="cpu" , UpperCAmelCase__ : Optional[Any]=torch.floataa , UpperCAmelCase__ : Optional[Any]=(1, 3, 6_4, 6_4) ) -> Tuple: __SCREAMING_SNAKE_CASE = torch.manual_seed(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "num_inference_steps": None, "timesteps": [2_2, 0], "class_labels": 0, "generator": generator, "output_type": "np", } if get_fixed_latents: __SCREAMING_SNAKE_CASE = self.get_fixed_latents(seed=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ , shape=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = latents return inputs def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str=0 , UpperCAmelCase__ : str="cpu" , UpperCAmelCase__ : Dict=torch.floataa , UpperCAmelCase__ : Union[str, Any]=(1, 3, 6_4, 6_4) ) -> List[Any]: if type(UpperCAmelCase__ ) == str: __SCREAMING_SNAKE_CASE = torch.device(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ , dtype=UpperCAmelCase__ ) return latents def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) __SCREAMING_SNAKE_CASE = CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.002 , sigma_max=80.0 , ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(torch_device=UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_inputs() __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.0_888, 0.0_881, 0.0_666, 0.0_479, 0.0_292, 0.0_195, 0.0_201, 0.0_163, 0.0_254] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) __SCREAMING_SNAKE_CASE = CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.002 , sigma_max=80.0 , ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(torch_device=UpperCAmelCase__ ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_inputs() __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.0_340, 0.0_152, 0.0_063, 0.0_267, 0.0_221, 0.0_107, 0.0_416, 0.0_186, 0.0_217] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 @require_torch_a def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) __SCREAMING_SNAKE_CASE = CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.002 , sigma_max=80.0 , ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(torch_device=UpperCAmelCase__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_inputs(get_fixed_latents=UpperCAmelCase__ , device=UpperCAmelCase__ ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=UpperCAmelCase__ , enable_math=UpperCAmelCase__ , enable_mem_efficient=UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.1_875, 0.1_428, 0.1_289, 0.2_151, 0.2_092, 0.1_477, 0.1_877, 0.1_641, 0.1_353] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 @require_torch_a def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = UNetaDModel.from_pretrained("diffusers/consistency_models" , subfolder="diffusers_cd_imagenet64_l2" ) __SCREAMING_SNAKE_CASE = CMStochasticIterativeScheduler( num_train_timesteps=4_0 , sigma_min=0.002 , sigma_max=80.0 , ) __SCREAMING_SNAKE_CASE = ConsistencyModelPipeline(unet=UpperCAmelCase__ , scheduler=UpperCAmelCase__ ) pipe.to(torch_device=UpperCAmelCase__ , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_inputs(get_fixed_latents=UpperCAmelCase__ , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=UpperCAmelCase__ , enable_math=UpperCAmelCase__ , enable_mem_efficient=UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = pipe(**UpperCAmelCase__ ).images assert image.shape == (1, 6_4, 6_4, 3) __SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] __SCREAMING_SNAKE_CASE = np.array([0.1_663, 0.1_948, 0.2_275, 0.1_680, 0.1_204, 0.1_245, 0.1_858, 0.1_338, 0.2_095] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 while len(lowerCAmelCase_ ) > 1: __SCREAMING_SNAKE_CASE = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): __SCREAMING_SNAKE_CASE = files.index(min(lowerCAmelCase_ ) ) temp += files[min_index] files.pop(lowerCAmelCase_ ) files.append(lowerCAmelCase_ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import math def UpperCAmelCase__ (lowerCAmelCase_ ): '''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(lowerCAmelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True a__ : int = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("n must be an integer" ) if n <= 0: raise ValueError("n must be >= 0" ) __SCREAMING_SNAKE_CASE = [] for num in range(len(lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = 0 while 2 * i * i <= odd_composites[num]: __SCREAMING_SNAKE_CASE = odd_composites[num] - 2 * i * i if is_prime(lowerCAmelCase_ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCAmelCase_ ) == n: return list_nums return [] def UpperCAmelCase__ (): '''simple docstring''' return compute_nums(1 )[0] if __name__ == "__main__": print(F"{solution() = }")
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "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, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""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. import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "naver-clova-ix/donut-base-finetuned-docvqa" snake_case__ : int = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) snake_case__ : int = "document_qa" snake_case__ : List[str] = AutoProcessor snake_case__ : Any = VisionEncoderDecoderModel snake_case__ : List[str] = ["image", "text"] snake_case__ : Optional[Any] = ["text"] def __init__( self : Optional[Any] , *UpperCAmelCase__ : Optional[int] , **UpperCAmelCase__ : Optional[int] ) -> List[str]: if not is_vision_available(): raise ValueError("Pillow must be installed to use the DocumentQuestionAnsweringTool." ) super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : "Image" , UpperCAmelCase__ : str ) -> List[Any]: __SCREAMING_SNAKE_CASE = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" __SCREAMING_SNAKE_CASE = task_prompt.replace("{user_input}" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.pre_processor.tokenizer( UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , return_tensors="pt" ).input_ids __SCREAMING_SNAKE_CASE = self.pre_processor(UpperCAmelCase__ , return_tensors="pt" ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Optional[int] ) -> Any: return self.model.generate( inputs["pixel_values"].to(self.device ) , decoder_input_ids=inputs["decoder_input_ids"].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=UpperCAmelCase__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=UpperCAmelCase__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=UpperCAmelCase__ , ).sequences def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Dict: __SCREAMING_SNAKE_CASE = self.pre_processor.batch_decode(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = sequence.replace(self.pre_processor.tokenizer.eos_token , "" ) __SCREAMING_SNAKE_CASE = sequence.replace(self.pre_processor.tokenizer.pad_token , "" ) __SCREAMING_SNAKE_CASE = re.sub(R"<.*?>" , "" , UpperCAmelCase__ , count=1 ).strip() # remove first task start token __SCREAMING_SNAKE_CASE = self.pre_processor.tokenajson(UpperCAmelCase__ ) return sequence["answer"]
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = (UniPCMultistepScheduler,) snake_case__ : Dict = (("num_inference_steps", 25),) def UpperCAmelCase_ ( self : Union[str, Any] , **UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = { "num_train_timesteps": 1_0_0_0, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", "solver_order": 2, "solver_type": "bh2", } config.update(**UpperCAmelCase__ ) return config def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[Any]=0 , **UpperCAmelCase__ : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE = kwargs.pop("num_inference_steps" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.dummy_sample __SCREAMING_SNAKE_CASE = 0.1 * sample __SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE = self.get_scheduler_config(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(UpperCAmelCase__ ) # copy over dummy past residuals __SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(UpperCAmelCase__ ) new_scheduler.set_timesteps(UpperCAmelCase__ ) # copy over dummy past residuals __SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sample, sample for t in range(UpperCAmelCase__ , time_step + scheduler.config.solver_order + 1 ): __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample __SCREAMING_SNAKE_CASE = new_scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any]=0 , **UpperCAmelCase__ : Optional[int] ) -> Any: __SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE = kwargs.pop("num_inference_steps" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.dummy_sample __SCREAMING_SNAKE_CASE = 0.1 * sample __SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(UpperCAmelCase__ ) # copy over dummy past residuals (must be after setting timesteps) __SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class.from_pretrained(UpperCAmelCase__ ) # copy over dummy past residuals new_scheduler.set_timesteps(UpperCAmelCase__ ) # copy over dummy past residual (must be after setting timesteps) __SCREAMING_SNAKE_CASE = dummy_past_residuals[: new_scheduler.config.solver_order] __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample __SCREAMING_SNAKE_CASE = new_scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: if scheduler is None: __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1_0 __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter scheduler.set_timesteps(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample return sample def UpperCAmelCase_ ( self : int ) -> Optional[int]: __SCREAMING_SNAKE_CASE = dict(self.forward_default_kwargs ) __SCREAMING_SNAKE_CASE = kwargs.pop("num_inference_steps" , UpperCAmelCase__ ) for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE = self.get_scheduler_config() __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.dummy_sample __SCREAMING_SNAKE_CASE = 0.1 * sample if num_inference_steps is not None and hasattr(UpperCAmelCase__ , "set_timesteps" ): scheduler.set_timesteps(UpperCAmelCase__ ) elif num_inference_steps is not None and not hasattr(UpperCAmelCase__ , "set_timesteps" ): __SCREAMING_SNAKE_CASE = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __SCREAMING_SNAKE_CASE = [residual + 0.2, residual + 0.15, residual + 0.10] __SCREAMING_SNAKE_CASE = dummy_past_residuals[: scheduler.config.solver_order] __SCREAMING_SNAKE_CASE = scheduler.timesteps[5] __SCREAMING_SNAKE_CASE = scheduler.timesteps[6] __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCAmelCase_ ( self : int ) -> Dict: # make sure that iterating over schedulers with same config names gives same results # for defaults __SCREAMING_SNAKE_CASE = UniPCMultistepScheduler(**self.get_scheduler_config() ) __SCREAMING_SNAKE_CASE = self.full_loop(scheduler=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_mean.item() - 0.2_464 ) < 1E-3 __SCREAMING_SNAKE_CASE = DPMSolverSinglestepScheduler.from_config(scheduler.config ) __SCREAMING_SNAKE_CASE = DEISMultistepScheduler.from_config(scheduler.config ) __SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(scheduler.config ) __SCREAMING_SNAKE_CASE = UniPCMultistepScheduler.from_config(scheduler.config ) __SCREAMING_SNAKE_CASE = self.full_loop(scheduler=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_mean.item() - 0.2_464 ) < 1E-3 def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: self.check_over_configs(thresholding=UpperCAmelCase__ ) for order in [1, 2, 3]: for solver_type in ["bh1", "bh2"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=UpperCAmelCase__ , prediction_type=UpperCAmelCase__ , sample_max_value=UpperCAmelCase__ , solver_order=UpperCAmelCase__ , solver_type=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: for solver_type in ["bh1", "bh2"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=UpperCAmelCase__ , solver_type=UpperCAmelCase__ , prediction_type=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = self.full_loop( solver_order=UpperCAmelCase__ , solver_type=UpperCAmelCase__ , prediction_type=UpperCAmelCase__ , ) assert not torch.isnan(UpperCAmelCase__ ).any(), "Samples have nan numbers" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: self.check_over_configs(lower_order_final=UpperCAmelCase__ ) self.check_over_configs(lower_order_final=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> List[Any]: for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=UpperCAmelCase__ , time_step=0 ) def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = self.full_loop() __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_mean.item() - 0.2_464 ) < 1E-3 def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.full_loop(prediction_type="v_prediction" ) __SCREAMING_SNAKE_CASE = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_mean.item() - 0.1_014 ) < 1E-3 def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: __SCREAMING_SNAKE_CASE = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE = self.get_scheduler_config(thresholding=UpperCAmelCase__ , dynamic_thresholding_ratio=0 ) __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 1_0 __SCREAMING_SNAKE_CASE = self.dummy_model() __SCREAMING_SNAKE_CASE = self.dummy_sample_deter.half() scheduler.set_timesteps(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler.step(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ).prev_sample assert sample.dtype == torch.floataa def UpperCAmelCase_ ( self : Union[str, Any] , **UpperCAmelCase__ : str ) -> List[Any]: for scheduler_class in self.scheduler_classes: __SCREAMING_SNAKE_CASE = self.get_scheduler_config(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(scheduler.config.num_train_timesteps ) assert len(scheduler.timesteps.unique() ) == scheduler.num_inference_steps
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" from ... import PretrainedConfig a__ : List[str] = { '''sijunhe/nezha-cn-base''': '''https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP snake_case__ : List[Any] = "nezha" def __init__( self : List[str] , UpperCAmelCase__ : List[Any]=2_1_1_2_8 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Union[str, Any]=1_2 , UpperCAmelCase__ : Optional[Any]=1_2 , UpperCAmelCase__ : int=3_0_7_2 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Optional[int]=0.1 , UpperCAmelCase__ : List[str]=5_1_2 , UpperCAmelCase__ : Optional[int]=6_4 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : List[Any]=1E-12 , UpperCAmelCase__ : int=0.1 , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=True , **UpperCAmelCase__ : List[str] , ) -> Optional[int]: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = max_relative_position __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = classifier_dropout __SCREAMING_SNAKE_CASE = use_cache
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. a__ : Dict = 2_0_0 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. a__ : List[Any] = 5_0 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. a__ : List[str] = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1_0_0_0)) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len([g for position, g in enumerate(lowerCAmelCase_ ) if g == main_target[position]] ) return (item, float(lowerCAmelCase_ )) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = random.randint(0 , len(lowerCAmelCase_ ) - 1 ) __SCREAMING_SNAKE_CASE = parent_a[:random_slice] + parent_a[random_slice:] __SCREAMING_SNAKE_CASE = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = list(lowerCAmelCase_ ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: __SCREAMING_SNAKE_CASE = random.choice(lowerCAmelCase_ ) return "".join(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] # Generate more children proportionally to the fitness score. __SCREAMING_SNAKE_CASE = int(parent_a[1] * 100 ) + 1 __SCREAMING_SNAKE_CASE = 10 if child_n >= 10 else child_n for _ in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = population_score[random.randint(0 , lowerCAmelCase_ )][0] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = crossover(parent_a[0] , lowerCAmelCase_ ) # Append new string to the population list. pop.append(mutate(lowerCAmelCase_ , lowerCAmelCase_ ) ) pop.append(mutate(lowerCAmelCase_ , lowerCAmelCase_ ) ) return pop def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = True ): '''simple docstring''' if N_POPULATION < N_SELECTED: __SCREAMING_SNAKE_CASE = f"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(lowerCAmelCase_ ) # Verify that the target contains no genes besides the ones inside genes variable. __SCREAMING_SNAKE_CASE = sorted({c for c in target if c not in genes} ) if not_in_genes_list: __SCREAMING_SNAKE_CASE = f"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(lowerCAmelCase_ ) # Generate random starting population. __SCREAMING_SNAKE_CASE = [] for _ in range(lowerCAmelCase_ ): population.append("".join([random.choice(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) )] ) ) # Just some logs to know what the algorithms is doing. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(lowerCAmelCase_ ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. __SCREAMING_SNAKE_CASE = [evaluate(lowerCAmelCase_ , lowerCAmelCase_ ) for item in population] # Check if there is a matching evolution. __SCREAMING_SNAKE_CASE = sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x[1] , reverse=lowerCAmelCase_ ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"""\nGeneration: {generation}""" f"""\nTotal Population:{total_population}""" f"""\nBest score: {population_score[0][1]}""" f"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. __SCREAMING_SNAKE_CASE = population[: int(N_POPULATION / 3 )] population.clear() population.extend(lowerCAmelCase_ ) # Normalize population score to be between 0 and 1. __SCREAMING_SNAKE_CASE = [ (item, score / len(lowerCAmelCase_ )) for item, score in population_score ] # This is selection for i in range(lowerCAmelCase_ ): population.extend(select(population_score[int(lowerCAmelCase_ )] , lowerCAmelCase_ , lowerCAmelCase_ ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(lowerCAmelCase_ ) > N_POPULATION: break if __name__ == "__main__": a__ : Union[str, Any] = ( '''This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!''' ) a__ : Dict = list( ''' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm''' '''nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\''' ) a__ , a__ , a__ : Any = basic(target_str, genes_list) print( F"\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}" )
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import inspect import unittest from transformers import RegNetConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import RegNetForImageClassification, RegNetModel from transformers.models.regnet.modeling_regnet import REGNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple=3 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : Optional[int]=3 , UpperCAmelCase__ : List[Any]=1_0 , UpperCAmelCase__ : Tuple=[1_0, 2_0, 3_0, 4_0] , UpperCAmelCase__ : Tuple=[1, 1, 2, 1] , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple="relu" , UpperCAmelCase__ : List[Any]=3 , UpperCAmelCase__ : List[Any]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = embeddings_size __SCREAMING_SNAKE_CASE = hidden_sizes __SCREAMING_SNAKE_CASE = depths __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = RegNetModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = RegNetForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Dict = (RegNetModel, RegNetForImageClassification) if is_torch_available() else () snake_case__ : Dict = ( {"feature-extraction": RegNetModel, "image-classification": RegNetForImageClassification} if is_torch_available() else {} ) snake_case__ : Optional[Any] = False snake_case__ : List[str] = False snake_case__ : Optional[int] = False snake_case__ : Optional[int] = False def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = RegNetModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: 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 UpperCAmelCase_ ( self : Optional[int] ) -> List[Any]: return @unittest.skip(reason="RegNet does not use inputs_embeds" ) def UpperCAmelCase_ ( self : str ) -> str: pass @unittest.skip(reason="RegNet does not support input and output embeddings" ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: pass def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) for name, module in model.named_modules(): if isinstance(UpperCAmelCase__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: def check_hidden_states_output(UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Optional[int] ): __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __SCREAMING_SNAKE_CASE = self.model_tester.num_stages self.assertEqual(len(UpperCAmelCase__ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = ["basic", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __SCREAMING_SNAKE_CASE = layer_type __SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __SCREAMING_SNAKE_CASE = True check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : str ) -> Optional[Any]: for model_name in REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = RegNetModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: return ( AutoImageProcessor.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RegNetForImageClassification.from_pretrained(REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="pt" ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([-0.4_180, -1.5_051, -3.4_836] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" 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 a__ : Dict = collections.namedtuple('''_Datasets''', ['''train''', '''validation''', '''test''']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ a__ : List[Any] = '''https://storage.googleapis.com/cvdf-datasets/mnist/''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = numpy.dtype(numpy.uintaa ).newbyteorder(">" ) return numpy.frombuffer(bytestream.read(4 ) , dtype=lowerCAmelCase_ )[0] @deprecated(lowerCAmelCase_ , "Please use tf.data to implement this functionality." ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' print("Extracting" , f.name ) with gzip.GzipFile(fileobj=lowerCAmelCase_ ) as bytestream: __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) if magic != 2051: raise ValueError( "Invalid magic number %d in MNIST image file: %s" % (magic, f.name) ) __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bytestream.read(rows * cols * num_images ) __SCREAMING_SNAKE_CASE = numpy.frombuffer(lowerCAmelCase_ , dtype=numpy.uinta ) __SCREAMING_SNAKE_CASE = data.reshape(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 1 ) return data @deprecated(lowerCAmelCase_ , "Please use tf.one_hot on tensors." ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = labels_dense.shape[0] __SCREAMING_SNAKE_CASE = numpy.arange(lowerCAmelCase_ ) * num_classes __SCREAMING_SNAKE_CASE = numpy.zeros((num_labels, num_classes) ) __SCREAMING_SNAKE_CASE = 1 return labels_one_hot @deprecated(lowerCAmelCase_ , "Please use tf.data to implement this functionality." ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=10 ): '''simple docstring''' print("Extracting" , f.name ) with gzip.GzipFile(fileobj=lowerCAmelCase_ ) as bytestream: __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) if magic != 2049: raise ValueError( "Invalid magic number %d in MNIST label file: %s" % (magic, f.name) ) __SCREAMING_SNAKE_CASE = _readaa(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = bytestream.read(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = numpy.frombuffer(lowerCAmelCase_ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(lowerCAmelCase_ , lowerCAmelCase_ ) return labels class UpperCamelCase_ : """simple docstring""" @deprecated( UpperCAmelCase__ , "Please use alternatives such as official/mnist/_DataSet.py" " from tensorflow/models." , ) def __init__( self : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : str=dtypes.floataa , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Dict=None , ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = random_seed.get_seed(UpperCAmelCase__ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __SCREAMING_SNAKE_CASE = dtypes.as_dtype(UpperCAmelCase__ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype ) if fake_data: __SCREAMING_SNAKE_CASE = 1_0_0_0_0 __SCREAMING_SNAKE_CASE = one_hot else: assert ( images.shape[0] == labels.shape[0] ), F"""images.shape: {images.shape} labels.shape: {labels.shape}""" __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __SCREAMING_SNAKE_CASE = images.astype(numpy.floataa ) __SCREAMING_SNAKE_CASE = numpy.multiply(UpperCAmelCase__ , 1.0 / 255.0 ) __SCREAMING_SNAKE_CASE = images __SCREAMING_SNAKE_CASE = labels __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 @property def UpperCAmelCase_ ( self : Dict ) -> Dict: return self._images @property def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: return self._labels @property def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: return self._num_examples @property def UpperCAmelCase_ ( self : Any ) -> Tuple: return self._epochs_completed def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : List[str]=True ) -> int: if fake_data: __SCREAMING_SNAKE_CASE = [1] * 7_8_4 __SCREAMING_SNAKE_CASE = [1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(UpperCAmelCase__ )], [fake_label for _ in range(UpperCAmelCase__ )], ) __SCREAMING_SNAKE_CASE = self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __SCREAMING_SNAKE_CASE = numpy.arange(self._num_examples ) numpy.random.shuffle(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.images[perma] __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = self._num_examples - start __SCREAMING_SNAKE_CASE = self._images[start : self._num_examples] __SCREAMING_SNAKE_CASE = self._labels[start : self._num_examples] # Shuffle the data if shuffle: __SCREAMING_SNAKE_CASE = numpy.arange(self._num_examples ) numpy.random.shuffle(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.images[perm] __SCREAMING_SNAKE_CASE = self.labels[perm] # Start next epoch __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = batch_size - rest_num_examples __SCREAMING_SNAKE_CASE = self._index_in_epoch __SCREAMING_SNAKE_CASE = self._images[start:end] __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE = self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(lowerCAmelCase_ , "Please write your own downloading logic." ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not gfile.Exists(lowerCAmelCase_ ): gfile.MakeDirs(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) if not gfile.Exists(lowerCAmelCase_ ): urllib.request.urlretrieve(lowerCAmelCase_ , lowerCAmelCase_ ) # noqa: S310 with gfile.GFile(lowerCAmelCase_ ) as f: __SCREAMING_SNAKE_CASE = f.size() print("Successfully downloaded" , lowerCAmelCase_ , lowerCAmelCase_ , "bytes." ) return filepath @deprecated( lowerCAmelCase_ , "Please use alternatives such as:" " tensorflow_datasets.load('mnist')" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=dtypes.floataa , lowerCAmelCase_=True , lowerCAmelCase_=5000 , lowerCAmelCase_=None , lowerCAmelCase_=DEFAULT_SOURCE_URL , ): '''simple docstring''' if fake_data: def fake(): return _DataSet( [] , [] , fake_data=lowerCAmelCase_ , one_hot=lowerCAmelCase_ , dtype=lowerCAmelCase_ , seed=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = fake() __SCREAMING_SNAKE_CASE = fake() __SCREAMING_SNAKE_CASE = fake() return _Datasets(train=lowerCAmelCase_ , validation=lowerCAmelCase_ , test=lowerCAmelCase_ ) if not source_url: # empty string check __SCREAMING_SNAKE_CASE = DEFAULT_SOURCE_URL __SCREAMING_SNAKE_CASE = "train-images-idx3-ubyte.gz" __SCREAMING_SNAKE_CASE = "train-labels-idx1-ubyte.gz" __SCREAMING_SNAKE_CASE = "t10k-images-idx3-ubyte.gz" __SCREAMING_SNAKE_CASE = "t10k-labels-idx1-ubyte.gz" __SCREAMING_SNAKE_CASE = _maybe_download( lowerCAmelCase_ , lowerCAmelCase_ , source_url + train_images_file ) with gfile.Open(lowerCAmelCase_ , "rb" ) as f: __SCREAMING_SNAKE_CASE = _extract_images(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _maybe_download( lowerCAmelCase_ , lowerCAmelCase_ , source_url + train_labels_file ) with gfile.Open(lowerCAmelCase_ , "rb" ) as f: __SCREAMING_SNAKE_CASE = _extract_labels(lowerCAmelCase_ , one_hot=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _maybe_download( lowerCAmelCase_ , lowerCAmelCase_ , source_url + test_images_file ) with gfile.Open(lowerCAmelCase_ , "rb" ) as f: __SCREAMING_SNAKE_CASE = _extract_images(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _maybe_download( lowerCAmelCase_ , lowerCAmelCase_ , source_url + test_labels_file ) with gfile.Open(lowerCAmelCase_ , "rb" ) as f: __SCREAMING_SNAKE_CASE = _extract_labels(lowerCAmelCase_ , one_hot=lowerCAmelCase_ ) if not 0 <= validation_size <= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = ( "Validation size should be between 0 and " f"""{len(lowerCAmelCase_ )}. Received: {validation_size}.""" ) raise ValueError(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = train_images[:validation_size] __SCREAMING_SNAKE_CASE = train_labels[:validation_size] __SCREAMING_SNAKE_CASE = train_images[validation_size:] __SCREAMING_SNAKE_CASE = train_labels[validation_size:] __SCREAMING_SNAKE_CASE = {"dtype": dtype, "reshape": reshape, "seed": seed} __SCREAMING_SNAKE_CASE = _DataSet(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _DataSet(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = _DataSet(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) return _Datasets(train=lowerCAmelCase_ , validation=lowerCAmelCase_ , test=lowerCAmelCase_ )
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" from collections import Counter from timeit import timeit def UpperCAmelCase__ (lowerCAmelCase_ = "" , ): '''simple docstring''' return sum(c % 2 for c in Counter(input_str.replace(" " , "" ).lower() ).values() ) < 2 def UpperCAmelCase__ (lowerCAmelCase_ = "" ): '''simple docstring''' if len(lowerCAmelCase_ ) == 0: return True __SCREAMING_SNAKE_CASE = input_str.replace(" " , "" ).lower() # character_freq_dict: Stores the frequency of every character in the input string __SCREAMING_SNAKE_CASE = {} for character in lower_case_input_str: __SCREAMING_SNAKE_CASE = character_freq_dict.get(lowerCAmelCase_ , 0 ) + 1 __SCREAMING_SNAKE_CASE = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def UpperCAmelCase__ (lowerCAmelCase_ = "" ): '''simple docstring''' print("\nFor string = " , lowerCAmelCase_ , ":" ) print( "> can_string_be_rearranged_as_palindrome_counter()" , "\tans =" , can_string_be_rearranged_as_palindrome_counter(lowerCAmelCase_ ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome_counter(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) print( "> can_string_be_rearranged_as_palindrome()" , "\tans =" , can_string_be_rearranged_as_palindrome(lowerCAmelCase_ ) , "\ttime =" , timeit( "z.can_string_be_rearranged_as_palindrome(z.check_str)" , setup="import __main__ as z" , ) , "seconds" , ) if __name__ == "__main__": a__ : List[Any] = input( '''Enter string to determine if it can be rearranged as a palindrome or not: ''' ).strip() benchmark(check_str) a__ : Dict = can_string_be_rearranged_as_palindrome_counter(check_str) print(F"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset from utils import logger class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] ) -> Dict: __SCREAMING_SNAKE_CASE = params __SCREAMING_SNAKE_CASE = np.array(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array([len(UpperCAmelCase__ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self : List[str] , UpperCAmelCase__ : str ) -> Optional[Any]: return (self.token_ids[index], self.lengths[index]) def __len__( self : Tuple ) -> List[str]: return len(self.lengths ) def UpperCAmelCase_ ( self : Dict ) -> Optional[int]: assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.params.max_model_input_size __SCREAMING_SNAKE_CASE = self.lengths > max_len logger.info(F"""Splitting {sum(UpperCAmelCase__ )} too long sequences.""" ) def divide_chunks(UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] ): return [l[i : i + n] for i in range(0 , len(UpperCAmelCase__ ) , UpperCAmelCase__ )] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] if self.params.mlm: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.params.special_tok_ids["cls_token"], self.params.special_tok_ids["sep_token"] else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.params.special_tok_ids["bos_token"], self.params.special_tok_ids["eos_token"] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: __SCREAMING_SNAKE_CASE = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: __SCREAMING_SNAKE_CASE = np.insert(UpperCAmelCase__ , 0 , UpperCAmelCase__ ) if sub_s[-1] != sep_id: __SCREAMING_SNAKE_CASE = np.insert(UpperCAmelCase__ , len(UpperCAmelCase__ ) , UpperCAmelCase__ ) assert len(UpperCAmelCase__ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(UpperCAmelCase__ ) new_tok_ids.extend(UpperCAmelCase__ ) new_lengths.extend([len(UpperCAmelCase__ ) for l in sub_seqs] ) __SCREAMING_SNAKE_CASE = np.array(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.array(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = len(self ) __SCREAMING_SNAKE_CASE = self.lengths > 1_1 __SCREAMING_SNAKE_CASE = self.token_ids[indices] __SCREAMING_SNAKE_CASE = self.lengths[indices] __SCREAMING_SNAKE_CASE = len(self ) logger.info(F"""Remove {init_size - new_size} too short (<=11 tokens) sequences.""" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: if "unk_token" not in self.params.special_tok_ids: return else: __SCREAMING_SNAKE_CASE = self.params.special_tok_ids["unk_token"] __SCREAMING_SNAKE_CASE = len(self ) __SCREAMING_SNAKE_CASE = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) __SCREAMING_SNAKE_CASE = (unk_occs / self.lengths) < 0.5 __SCREAMING_SNAKE_CASE = self.token_ids[indices] __SCREAMING_SNAKE_CASE = self.lengths[indices] __SCREAMING_SNAKE_CASE = len(self ) logger.info(F"""Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).""" ) def UpperCAmelCase_ ( self : List[Any] ) -> int: if not self.params.is_master: return logger.info(F"""{len(self )} sequences""" ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = [t[0] for t in batch] __SCREAMING_SNAKE_CASE = [t[1] for t in batch] assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ) # Max for paddings __SCREAMING_SNAKE_CASE = max(UpperCAmelCase__ ) # Pad token ids if self.params.mlm: __SCREAMING_SNAKE_CASE = self.params.special_tok_ids["pad_token"] else: __SCREAMING_SNAKE_CASE = self.params.special_tok_ids["unk_token"] __SCREAMING_SNAKE_CASE = [list(t.astype(UpperCAmelCase__ ) ) + [pad_idx] * (max_seq_len_ - len(UpperCAmelCase__ )) for t in token_ids] assert len(tk_ ) == len(UpperCAmelCase__ ) assert all(len(UpperCAmelCase__ ) == max_seq_len_ for t in tk_ ) __SCREAMING_SNAKE_CASE = torch.tensor(tk_ ) # (bs, max_seq_len_) __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) # (bs) return tk_t, lg_t
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" 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 a__ : Tuple = True except (ImportError, AttributeError): a__ : Optional[int] = object def UpperCAmelCase__ (*lowerCAmelCase_ , **lowerCAmelCase_ ): '''simple docstring''' pass a__ : List[Any] = False a__ : Any = logging.get_logger('''transformers-cli/serving''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''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(lowerCAmelCase_ , args.host , args.port , args.workers ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : dict class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] snake_case__ : Optional[List[int]] class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @staticmethod def UpperCAmelCase_ ( UpperCAmelCase__ : ArgumentParser ) -> Optional[int]: __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=UpperCAmelCase__ , choices=get_supported_tasks() , help="The task to run the pipeline on" , ) serve_parser.add_argument("--host" , type=UpperCAmelCase__ , default="localhost" , help="Interface the server will listen on." ) serve_parser.add_argument("--port" , type=UpperCAmelCase__ , default=8_8_8_8 , help="Port the serving will listen to." ) serve_parser.add_argument("--workers" , type=UpperCAmelCase__ , default=1 , help="Number of http workers" ) serve_parser.add_argument("--model" , type=UpperCAmelCase__ , help="Model's name or path to stored model." ) serve_parser.add_argument("--config" , type=UpperCAmelCase__ , help="Model's config name or path to stored model." ) serve_parser.add_argument("--tokenizer" , type=UpperCAmelCase__ , help="Tokenizer name to use." ) serve_parser.add_argument( "--device" , type=UpperCAmelCase__ , default=-1 , help="Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)" , ) serve_parser.set_defaults(func=UpperCAmelCase__ ) def __init__( self : Optional[Any] , UpperCAmelCase__ : Pipeline , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __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=UpperCAmelCase__ , response_class=UpperCAmelCase__ , methods=["GET"] , ), APIRoute( "/tokenize" , self.tokenize , response_model=UpperCAmelCase__ , response_class=UpperCAmelCase__ , methods=["POST"] , ), APIRoute( "/detokenize" , self.detokenize , response_model=UpperCAmelCase__ , response_class=UpperCAmelCase__ , methods=["POST"] , ), APIRoute( "/forward" , self.forward , response_model=UpperCAmelCase__ , response_class=UpperCAmelCase__ , methods=["POST"] , ), ] , timeout=6_0_0 , ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: run(self._app , host=self.host , port=self.port , workers=self.workers ) def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str = Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) , UpperCAmelCase__ : bool = Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) ) -> Union[str, Any]: try: __SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.tokenize(UpperCAmelCase__ ) if return_ids: __SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) return ServeTokenizeResult(tokens=UpperCAmelCase__ , tokens_ids=UpperCAmelCase__ ) else: return ServeTokenizeResult(tokens=UpperCAmelCase__ ) except Exception as e: raise HTTPException(status_code=5_0_0 , detail={"model": "", "error": str(UpperCAmelCase__ )} ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[int] = Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) , UpperCAmelCase__ : bool = Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) , UpperCAmelCase__ : bool = Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) , ) -> List[str]: try: __SCREAMING_SNAKE_CASE = self._pipeline.tokenizer.decode(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) return ServeDeTokenizeResult(model="" , text=UpperCAmelCase__ ) except Exception as e: raise HTTPException(status_code=5_0_0 , detail={"model": "", "error": str(UpperCAmelCase__ )} ) async def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=Body(UpperCAmelCase__ , embed=UpperCAmelCase__ ) ) -> Tuple: # Check we don't have empty string if len(UpperCAmelCase__ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __SCREAMING_SNAKE_CASE = self._pipeline(UpperCAmelCase__ ) return ServeForwardResult(output=UpperCAmelCase__ ) except Exception as e: raise HTTPException(5_0_0 , {"error": str(UpperCAmelCase__ )} )
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : List[str] = { '''configuration_vision_encoder_decoder''': ['''VisionEncoderDecoderConfig''', '''VisionEncoderDecoderOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = ['''VisionEncoderDecoderModel'''] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : List[str] = ['''TFVisionEncoderDecoderModel'''] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = ['''FlaxVisionEncoderDecoderModel'''] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = "laion/clap-htsat-unfused" __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() def UpperCAmelCase_ ( self : Optional[Any] , **UpperCAmelCase__ : Optional[int] ) -> Dict: return RobertaTokenizer.from_pretrained(self.checkpoint , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , **UpperCAmelCase__ : Tuple ) -> Union[str, Any]: return ClapFeatureExtractor.from_pretrained(self.checkpoint , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_feature_extractor() __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) __SCREAMING_SNAKE_CASE = self.get_feature_extractor(do_normalize=UpperCAmelCase__ , padding_value=1.0 ) __SCREAMING_SNAKE_CASE = ClapProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_feature_extractor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = floats_list((3, 1_0_0_0) ) __SCREAMING_SNAKE_CASE = feature_extractor(UpperCAmelCase__ , return_tensors="np" ) __SCREAMING_SNAKE_CASE = processor(audios=UpperCAmelCase__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ ( self : Dict ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_feature_extractor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "This is a test string" __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: __SCREAMING_SNAKE_CASE = self.get_feature_extractor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_feature_extractor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ClapProcessor(tokenizer=UpperCAmelCase__ , feature_extractor=UpperCAmelCase__ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , )
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise if not is_sharded: __SCREAMING_SNAKE_CASE = os.path.abspath(lowerCAmelCase_ ) logger.info(f"""Loading PyTorch weights from {pt_path}""" ) __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ , map_location="cpu" ) logger.info(f"""PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values() ):,} parameters.""" ) __SCREAMING_SNAKE_CASE = convert_pytorch_state_dict_to_flax(lowerCAmelCase_ , lowerCAmelCase_ ) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files __SCREAMING_SNAKE_CASE = convert_pytorch_sharded_state_dict_to_flax(lowerCAmelCase_ , lowerCAmelCase_ ) return flax_state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' def is_key_or_prefix_key_in_dict(lowerCAmelCase_ ) -> bool: return len(set(lowerCAmelCase_ ) & {key, (model_prefix,) + key} ) > 0 # layer norm __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): return renamed_pt_tuple_key, pt_tensor # batch norm layer var __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): return renamed_pt_tuple_key, pt_tensor # embedding __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): return renamed_pt_tuple_key, pt_tensor # conv layer __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pt_tensor.transpose(2 , 3 , 1 , 0 ) return renamed_pt_tuple_key, pt_tensor # linear layer __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias __SCREAMING_SNAKE_CASE = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 __SCREAMING_SNAKE_CASE = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): __SCREAMING_SNAKE_CASE = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): __SCREAMING_SNAKE_CASE = pt_tuple_key[-2] + "_v" if name is not None: __SCREAMING_SNAKE_CASE = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {k: v.numpy() for k, v in pt_state_dict.items()} __SCREAMING_SNAKE_CASE = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: __SCREAMING_SNAKE_CASE = flax_model.params["params"] else: __SCREAMING_SNAKE_CASE = flax_model.params __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: __SCREAMING_SNAKE_CASE = flatten_dict(flax_model.params["batch_stats"] ) random_flax_state_dict.update(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) __SCREAMING_SNAKE_CASE = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): __SCREAMING_SNAKE_CASE = tuple(pt_key.split("." ) ) # remove base model prefix if necessary __SCREAMING_SNAKE_CASE = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: __SCREAMING_SNAKE_CASE = pt_tuple_key[1:] # Correctly rename weight parameters __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rename_key_and_reshape_tensor( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # add model prefix if necessary __SCREAMING_SNAKE_CASE = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: __SCREAMING_SNAKE_CASE = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) continue # also add unexpected weight so that warning is thrown __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) else: # also add unexpected weight so that warning is thrown __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) return unflatten_dict(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' import torch # Load the index __SCREAMING_SNAKE_CASE = {} for shard_file in shard_filenames: # load using msgpack utils __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {k: v.numpy() for k, v in pt_state_dict.items()} __SCREAMING_SNAKE_CASE = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: __SCREAMING_SNAKE_CASE = flax_model.params["params"] __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"] ) ) else: __SCREAMING_SNAKE_CASE = flax_model.params __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = (model_prefix not in flax_model_params) and ( model_prefix in {k.split("." )[0] for k in pt_state_dict.keys()} ) __SCREAMING_SNAKE_CASE = (model_prefix in flax_model_params) and ( model_prefix not in {k.split("." )[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): __SCREAMING_SNAKE_CASE = tuple(pt_key.split("." ) ) # remove base model prefix if necessary __SCREAMING_SNAKE_CASE = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: __SCREAMING_SNAKE_CASE = pt_tuple_key[1:] # Correctly rename weight parameters __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = rename_key_and_reshape_tensor( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # add model prefix if necessary __SCREAMING_SNAKE_CASE = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: __SCREAMING_SNAKE_CASE = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """ f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) continue if "var" in flax_key[-1]: __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) continue # also add unexpected weight so that warning is thrown __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) else: # also add unexpected weight so that warning is thrown __SCREAMING_SNAKE_CASE = jnp.asarray(lowerCAmelCase_ ) return unflatten_dict(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = os.path.abspath(lowerCAmelCase_ ) logger.info(f"""Loading Flax weights from {flax_checkpoint_path}""" ) # import correct flax class __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "Flax" + model.__class__.__name__ ) # load flax weight dict with open(lowerCAmelCase_ , "rb" ) as state_f: try: __SCREAMING_SNAKE_CASE = from_bytes(lowerCAmelCase_ , state_f.read() ) except UnpicklingError: raise EnvironmentError(f"""Unable to convert {flax_checkpoint_path} to Flax deserializable object. """ ) return load_flax_weights_in_pytorch_model(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions." ) raise # check if we have bf16 weights __SCREAMING_SNAKE_CASE = flatten_dict(jax.tree_util.tree_map(lambda lowerCAmelCase_ : x.dtype == jnp.bfloataa , lowerCAmelCase_ ) ).values() if any(lowerCAmelCase_ ): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model." ) __SCREAMING_SNAKE_CASE = jax.tree_util.tree_map( lambda lowerCAmelCase_ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = pt_model.state_dict() __SCREAMING_SNAKE_CASE = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split("." )[0] for k in pt_model_dict.keys()} ) __SCREAMING_SNAKE_CASE = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split("." )[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): __SCREAMING_SNAKE_CASE = flax_key_tuple[0] == pt_model.base_model_prefix __SCREAMING_SNAKE_CASE = ".".join((pt_model.base_model_prefix,) + flax_key_tuple ) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: __SCREAMING_SNAKE_CASE = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: __SCREAMING_SNAKE_CASE = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(lowerCAmelCase_ ) not in pt_model_dict: # conv layer __SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ("weight",) __SCREAMING_SNAKE_CASE = jnp.transpose(lowerCAmelCase_ , (3, 2, 0, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(lowerCAmelCase_ ) not in pt_model_dict: # linear layer __SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ("weight",) __SCREAMING_SNAKE_CASE = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: __SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: __SCREAMING_SNAKE_CASE = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: __SCREAMING_SNAKE_CASE = ".".join(flax_key_tuple[1:] ) # Remove the params/batch_stats header else: __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. __SCREAMING_SNAKE_CASE = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: __SCREAMING_SNAKE_CASE = key.split("." ) __SCREAMING_SNAKE_CASE = None if key_components[-3::2] == ["parametrizations", "original0"]: __SCREAMING_SNAKE_CASE = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: __SCREAMING_SNAKE_CASE = key_components[-2] + "_v" if name is not None: __SCREAMING_SNAKE_CASE = key_components[:-3] + [name] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = key if flax_key in special_pt_names: __SCREAMING_SNAKE_CASE = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"""Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected """ f"""to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.""" ) else: # add weight to pytorch dict __SCREAMING_SNAKE_CASE = np.asarray(lowerCAmelCase_ ) if not isinstance(lowerCAmelCase_ , np.ndarray ) else flax_tensor __SCREAMING_SNAKE_CASE = torch.from_numpy(lowerCAmelCase_ ) # remove from missing keys missing_keys.remove(lowerCAmelCase_ ) else: # weight is not expected by PyTorch model unexpected_keys.append(lowerCAmelCase_ ) pt_model.load_state_dict(lowerCAmelCase_ ) # re-transform missing_keys to list __SCREAMING_SNAKE_CASE = list(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f""" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing""" f""" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture""" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f""" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect""" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model)." ) else: logger.warning(f"""All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n""" ) if len(lowerCAmelCase_ ) > 0: logger.warning( f"""Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly""" f""" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to""" " use it for predictions and inference." ) else: logger.warning( f"""All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n""" "If your task is similar to the task the model of the checkpoint was trained on, " f"""you can already use {pt_model.__class__.__name__} for predictions without further training.""" ) return pt_model
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , 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 UpperCAmelCase_ ( self : List[Any] ) -> str: 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 UpperCAmelCase_ ( self : List[Any] ) -> List[str]: 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 UpperCAmelCase_ ( self : List[str] ) -> Tuple: 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 UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: a__ : Tuple = None a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Union[str, Any] = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} a__ : List[str] = { '''vocab_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/spiece.model''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/spiece.model''', }, '''tokenizer_file''': { '''google/fnet-base''': '''https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json''', '''google/fnet-large''': '''https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json''', }, } a__ : List[Any] = { '''google/fnet-base''': 5_1_2, '''google/fnet-large''': 5_1_2, } a__ : Tuple = '''▁''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = VOCAB_FILES_NAMES snake_case__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = ["input_ids", "token_type_ids"] snake_case__ : Dict = FNetTokenizer def __init__( self : Tuple , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : Union[str, Any]=False , UpperCAmelCase__ : int=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : List[Any]="<unk>" , UpperCAmelCase__ : List[Any]="[SEP]" , UpperCAmelCase__ : Dict="<pad>" , UpperCAmelCase__ : Tuple="[CLS]" , UpperCAmelCase__ : Tuple="[MASK]" , **UpperCAmelCase__ : Union[str, Any] , ) -> List[Any]: # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. __SCREAMING_SNAKE_CASE = ( AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ , normalized=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token ) super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , remove_space=UpperCAmelCase__ , keep_accents=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = do_lower_case __SCREAMING_SNAKE_CASE = remove_space __SCREAMING_SNAKE_CASE = keep_accents __SCREAMING_SNAKE_CASE = vocab_file __SCREAMING_SNAKE_CASE = False if not self.vocab_file else True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase__ ): copyfile(self.vocab_file , UpperCAmelCase__ ) return (out_vocab_file,)
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) while cur > 1: # Find the maximum number in arr __SCREAMING_SNAKE_CASE = arr.index(max(arr[0:cur] ) ) # Reverse from 0 to mi __SCREAMING_SNAKE_CASE = arr[mi::-1] + arr[mi + 1 : len(lowerCAmelCase_ )] # Reverse whole list __SCREAMING_SNAKE_CASE = arr[cur - 1 :: -1] + arr[cur : len(lowerCAmelCase_ )] cur -= 1 return arr if __name__ == "__main__": a__ : str = input('''Enter numbers separated by a comma:\n''').strip() a__ : List[Any] = [int(item) for item in user_input.split(''',''')] print(pancake_sort(unsorted))
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if not nums: return 0 __SCREAMING_SNAKE_CASE = nums[0] __SCREAMING_SNAKE_CASE = 0 for num in nums[1:]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ( max_excluding + num, max(lowerCAmelCase_ , lowerCAmelCase_ ), ) return max(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import inspect import unittest from transformers import ViTHybridConfig from transformers.testing_utils import require_accelerate, require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple=1_3 , UpperCAmelCase__ : Dict=6_4 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : Optional[Any]=3 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Optional[Any]=3_2 , UpperCAmelCase__ : Optional[int]=5 , UpperCAmelCase__ : int=4 , UpperCAmelCase__ : List[str]=3_7 , UpperCAmelCase__ : List[str]="gelu" , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Union[str, Any]=1_0 , UpperCAmelCase__ : Optional[Any]=0.02 , UpperCAmelCase__ : Tuple=[1, 1_6, 4, 4] , UpperCAmelCase__ : Dict=None , ) -> List[str]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = patch_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = scope __SCREAMING_SNAKE_CASE = backbone_featmap_shape # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) # the number of patches is based on the feature map of the backbone, which by default uses an output stride # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size __SCREAMING_SNAKE_CASE = (self.image_size // 3_2) ** 2 __SCREAMING_SNAKE_CASE = num_patches + 1 def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = { "global_padding": "same", "layer_type": "bottleneck", "depths": [3, 4, 9], "out_features": ["stage1", "stage2", "stage3"], "embedding_dynamic_padding": True, "hidden_sizes": [4, 8, 1_6, 3_2], "num_groups": 2, } return ViTHybridConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , backbone_featmap_shape=self.backbone_featmap_shape , backbone_config=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = ViTHybridModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : str , UpperCAmelCase__ : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.type_sequence_label_size __SCREAMING_SNAKE_CASE = ViTHybridForImageClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Tuple = (ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else () snake_case__ : Dict = ( {"feature-extraction": ViTHybridModel, "image-classification": ViTHybridForImageClassification} if is_torch_available() else {} ) snake_case__ : List[str] = False snake_case__ : Tuple = False snake_case__ : Tuple = False def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = ViTHybridModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> int: self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def UpperCAmelCase_ ( self : str ) -> Optional[int]: pass def UpperCAmelCase_ ( self : str ) -> int: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __SCREAMING_SNAKE_CASE = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase__ , nn.Linear ) ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = _config_zero_init(UpperCAmelCase__ ) for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) # Skip the check for the backbone for name, module in model.named_modules(): if module.__class__.__name__ == "ViTHybridPatchEmbeddings": __SCREAMING_SNAKE_CASE = [F"""{name}.{key}""" for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> int: for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = ViTHybridModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @cached_property def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: return ( ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to( UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.default_image_processor __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="pt" ).to(UpperCAmelCase__ ) # forward pass with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) # verify the logits __SCREAMING_SNAKE_CASE = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([-1.9_090, -0.4_993, -0.2_389] ).to(UpperCAmelCase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow @require_accelerate def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384" ) __SCREAMING_SNAKE_CASE = ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384" , device_map="auto" ) __SCREAMING_SNAKE_CASE = prepare_img() __SCREAMING_SNAKE_CASE = image_processor(images=UpperCAmelCase__ , return_tensors="pt" ) __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.logits # model predicts one of the 1000 ImageNet classes __SCREAMING_SNAKE_CASE = logits.argmax(-1 ).item() self.assertTrue(model.config.idalabel[predicted_class_idx] , "tabby, tabby cat" )
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class UpperCamelCase_ : """simple docstring""" @property def UpperCAmelCase_ ( self : Union[str, Any] ) -> Dict: return self.get_dummy_input() @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F"""'{self.block_type}' is not a supported block_type. Set it to 'up', 'mid', or 'down'.""" ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=True , UpperCAmelCase__ : int=False , UpperCAmelCase__ : Optional[Any]=False , UpperCAmelCase__ : Any=False , ) -> List[str]: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3_2 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.device(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (batch_size, num_channels) + sizes __SCREAMING_SNAKE_CASE = randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = {"hidden_states": hidden_states} if include_temb: __SCREAMING_SNAKE_CASE = 1_2_8 __SCREAMING_SNAKE_CASE = randn_tensor((batch_size, temb_channels) , generator=UpperCAmelCase__ , device=UpperCAmelCase__ ) if include_res_hidden_states_tuple: __SCREAMING_SNAKE_CASE = torch.manual_seed(1 ) __SCREAMING_SNAKE_CASE = (randn_tensor(UpperCAmelCase__ , generator=UpperCAmelCase__ , device=UpperCAmelCase__ ),) if include_encoder_hidden_states: __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, 3_2, 3_2) ).to(UpperCAmelCase__ ) if include_skip_sample: __SCREAMING_SNAKE_CASE = randn_tensor(((batch_size, 3) + sizes) , generator=UpperCAmelCase__ , device=UpperCAmelCase__ ) return dummy_input def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = { "in_channels": 3_2, "out_channels": 3_2, "temb_channels": 1_2_8, } if self.block_type == "up": __SCREAMING_SNAKE_CASE = 3_2 if self.block_type == "mid": init_dict.pop("out_channels" ) __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.block_class(**UpperCAmelCase__ ) unet_block.to(UpperCAmelCase__ ) unet_block.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = unet_block(**UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = output[0] self.assertEqual(output.shape , self.output_shape ) __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:] __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ).to(UpperCAmelCase__ ) assert torch_all_close(output_slice.flatten() , UpperCAmelCase__ , atol=5E-3 ) @unittest.skipIf(torch_device == "mps" , "Training is not supported in mps" ) def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.block_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.train() __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = output[0] __SCREAMING_SNAKE_CASE = torch.device(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = randn_tensor(output.shape , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.nn.functional.mse_loss(UpperCAmelCase__ , UpperCAmelCase__ ) loss.backward()
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __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 = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch("socket.socket" ) @patch("builtins.open" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = Mock() __SCREAMING_SNAKE_CASE = conn, Mock() __SCREAMING_SNAKE_CASE = iter([1, None] ) __SCREAMING_SNAKE_CASE = lambda lowerCAmelCase_ : next(lowerCAmelCase_ ) # ===== invoke ===== send_file(filename="mytext.txt" , testing=lowerCAmelCase_ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import re def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = re.compile(R"^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$" ) if match := re.search(lowerCAmelCase_ , lowerCAmelCase_ ): return match.string == phone return False if __name__ == "__main__": print(indian_phone_validator('''+918827897895'''))
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(lowerCAmelCase_ , n - 1 , lowerCAmelCase_ ) * a) % mod else: __SCREAMING_SNAKE_CASE = binary_exponentiation(lowerCAmelCase_ , n / 2 , lowerCAmelCase_ ) return (b * b) % mod # a prime number a__ : List[Any] = 7_0_1 a__ : str = 1_0_0_0_0_0_0_0_0_0 a__ : Dict = 1_0 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 10 ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or n < 0: raise ValueError("Invalid input" ) __SCREAMING_SNAKE_CASE = 10**n __SCREAMING_SNAKE_CASE = 2_8433 * (pow(2 , 783_0457 , lowerCAmelCase_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"{solution(1_0) = }")
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : Any ) -> Tuple: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModel.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModel.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Any: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForPreTraining.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForPreTraining.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForCausalLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoModelForCausalLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : str ) -> List[Any]: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> str: for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForMaskedLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = TFAutoModelForSeqaSeqLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_pretrained( UpperCAmelCase__ , output_loading_info=UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForSequenceClassification.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFAutoModelForQuestionAnswering.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoModelForQuestionAnswering.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase__ ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE = AutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase__ ) , 1_4_4_1_0 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_pt=UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase__ ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE = AutoModelWithLMHead.from_pretrained(UpperCAmelCase__ , from_tf=UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase__ ) , 1_4_4_1_0 )
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "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, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" # Imports import numpy as np class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : List[Any]=None ) -> str: self.set_matricies(red=UpperCAmelCase__ , green=UpperCAmelCase__ , blue=UpperCAmelCase__ , red_edge=UpperCAmelCase__ , nir=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Optional[Any]=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Union[str, Any]=None ) -> Tuple: if red is not None: __SCREAMING_SNAKE_CASE = red if green is not None: __SCREAMING_SNAKE_CASE = green if blue is not None: __SCREAMING_SNAKE_CASE = blue if red_edge is not None: __SCREAMING_SNAKE_CASE = red_edge if nir is not None: __SCREAMING_SNAKE_CASE = nir return True def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Any="" , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[str]=None ) -> Optional[int]: self.set_matricies(red=UpperCAmelCase__ , green=UpperCAmelCase__ , blue=UpperCAmelCase__ , red_edge=UpperCAmelCase__ , nir=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = { "ARVI2": self.arvaa, "CCCI": self.ccci, "CVI": self.cvi, "GLI": self.gli, "NDVI": self.ndvi, "BNDVI": self.bndvi, "redEdgeNDVI": self.red_edge_ndvi, "GNDVI": self.gndvi, "GBNDVI": self.gbndvi, "GRNDVI": self.grndvi, "RBNDVI": self.rbndvi, "PNDVI": self.pndvi, "ATSAVI": self.atsavi, "BWDRVI": self.bwdrvi, "CIgreen": self.ci_green, "CIrededge": self.ci_rededge, "CI": self.ci, "CTVI": self.ctvi, "GDVI": self.gdvi, "EVI": self.evi, "GEMI": self.gemi, "GOSAVI": self.gosavi, "GSAVI": self.gsavi, "Hue": self.hue, "IVI": self.ivi, "IPVI": self.ipvi, "I": self.i, "RVI": self.rvi, "MRVI": self.mrvi, "MSAVI": self.m_savi, "NormG": self.norm_g, "NormNIR": self.norm_nir, "NormR": self.norm_r, "NGRDI": self.ngrdi, "RI": self.ri, "S": self.s, "IF": self._if, "DVI": self.dvi, "TVI": self.tvi, "NDRE": self.ndre, } try: return funcs[index]() except KeyError: print("Index not in the list!" ) return False def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def UpperCAmelCase_ ( self : List[str] ) -> int: return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def UpperCAmelCase_ ( self : Dict ) -> str: return self.nir * (self.red / (self.green**2)) def UpperCAmelCase_ ( self : Dict ) -> List[Any]: return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def UpperCAmelCase_ ( self : Tuple ) -> int: return (self.nir - self.red) / (self.nir + self.red) def UpperCAmelCase_ ( self : Tuple ) -> Tuple: return (self.nir - self.blue) / (self.nir + self.blue) def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return (self.redEdge - self.red) / (self.redEdge + self.red) def UpperCAmelCase_ ( self : Dict ) -> Any: return (self.nir - self.green) / (self.nir + self.green) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def UpperCAmelCase_ ( self : List[str] ) -> Dict: return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Any=0.08 , UpperCAmelCase__ : Optional[Any]=1.22 , UpperCAmelCase__ : Any=0.03 ) -> Any: return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def UpperCAmelCase_ ( self : str ) -> str: return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def UpperCAmelCase_ ( self : Optional[int] ) -> Any: return (self.nir / self.green) - 1 def UpperCAmelCase_ ( self : Tuple ) -> int: return (self.nir / self.redEdge) - 1 def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: return (self.red - self.blue) / self.red def UpperCAmelCase_ ( self : List[str] ) -> int: __SCREAMING_SNAKE_CASE = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: return self.nir - self.green def UpperCAmelCase_ ( self : str ) -> Dict: return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict=0.16 ) -> Union[str, Any]: return (self.nir - self.green) / (self.nir + self.green + y) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any]=0.5 ) -> Dict: return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def UpperCAmelCase_ ( self : str ) -> List[Any]: return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : Optional[Any]=None ) -> Tuple: return (self.nir - b) / (a * self.red) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return (self.red + self.green + self.blue) / 30.5 def UpperCAmelCase_ ( self : str ) -> Tuple: return self.nir / self.red def UpperCAmelCase_ ( self : List[Any] ) -> Union[str, Any]: return (self.rvi() - 1) / (self.rvi() + 1) def UpperCAmelCase_ ( self : str ) -> List[str]: return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def UpperCAmelCase_ ( self : List[Any] ) -> str: return self.green / (self.nir + self.red + self.green) def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: return self.nir / (self.nir + self.red + self.green) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: return self.red / (self.nir + self.red + self.green) def UpperCAmelCase_ ( self : int ) -> Any: return (self.green - self.red) / (self.green + self.red) def UpperCAmelCase_ ( self : int ) -> Any: return (self.red - self.green) / (self.red + self.green) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) __SCREAMING_SNAKE_CASE = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def UpperCAmelCase_ ( self : Optional[Any] ) -> Union[str, Any]: return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: return self.nir / self.red def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: return (self.ndvi() + 0.5) ** (1 / 2) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: return (self.nir - self.redEdge) / (self.nir + self.redEdge)
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import unittest from .lib import ( Matrix, Vector, axpy, square_zero_matrix, unit_basis_vector, zero_vector, ) class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : int ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) self.assertEqual(x.component(0 ) , 1 ) self.assertEqual(x.component(2 ) , 3 ) __SCREAMING_SNAKE_CASE = Vector() def UpperCAmelCase_ ( self : Any ) -> None: __SCREAMING_SNAKE_CASE = Vector([0, 0, 0, 0, 0, 1] ) self.assertEqual(str(UpperCAmelCase__ ) , "(0,0,0,0,0,1)" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3, 4] ) self.assertEqual(len(UpperCAmelCase__ ) , 4 ) def UpperCAmelCase_ ( self : int ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2] ) __SCREAMING_SNAKE_CASE = Vector([1, 2, 3, 4, 5] ) __SCREAMING_SNAKE_CASE = Vector([0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ) __SCREAMING_SNAKE_CASE = Vector([1, -1, 1, -1, 2, -3, 4, -5] ) self.assertAlmostEqual(x.euclidean_length() , 2.236 , 3 ) self.assertAlmostEqual(y.euclidean_length() , 7.416 , 3 ) self.assertEqual(z.euclidean_length() , 0 ) self.assertAlmostEqual(w.euclidean_length() , 7.616 , 3 ) def UpperCAmelCase_ ( self : Any ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 1, 1] ) self.assertEqual((x + y).component(0 ) , 2 ) self.assertEqual((x + y).component(1 ) , 3 ) self.assertEqual((x + y).component(2 ) , 4 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 1, 1] ) self.assertEqual((x - y).component(0 ) , 0 ) self.assertEqual((x - y).component(1 ) , 1 ) self.assertEqual((x - y).component(2 ) , 2 ) def UpperCAmelCase_ ( self : Optional[int] ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([2, -1, 4] ) # for test of dot product __SCREAMING_SNAKE_CASE = Vector([1, -2, -1] ) self.assertEqual(str(x * 3.0 ) , "(3.0,6.0,9.0)" ) self.assertEqual((a * b) , 0 ) def UpperCAmelCase_ ( self : List[Any] ) -> None: self.assertEqual(str(zero_vector(1_0 ) ).count("0" ) , 1_0 ) def UpperCAmelCase_ ( self : int ) -> None: self.assertEqual(str(unit_basis_vector(3 , 1 ) ) , "(0,1,0)" ) def UpperCAmelCase_ ( self : Dict ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) __SCREAMING_SNAKE_CASE = Vector([1, 0, 1] ) self.assertEqual(str(axpy(2 , UpperCAmelCase__ , UpperCAmelCase__ ) ) , "(3,4,7)" ) def UpperCAmelCase_ ( self : str ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 0, 0, 0, 0, 0] ) __SCREAMING_SNAKE_CASE = x.copy() self.assertEqual(str(UpperCAmelCase__ ) , str(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Tuple ) -> None: __SCREAMING_SNAKE_CASE = Vector([1, 0, 0] ) x.change_component(0 , 0 ) x.change_component(1 , 1 ) self.assertEqual(str(UpperCAmelCase__ ) , "(0,1,0)" ) def UpperCAmelCase_ ( self : int ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual("|1,2,3|\n|2,4,5|\n|6,7,8|\n" , str(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Dict ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = [[-3, -1_4, -1_0], [-5, -1_0, -5], [-2, -1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(minors[x][y] , a.minor(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Tuple ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = [[-3, 1_4, -1_0], [5, -1_0, 5], [-2, 1, 0]] for x in range(a.height() ): for y in range(a.width() ): self.assertEqual(cofactors[x][y] , a.cofactor(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(-5 , a.determinant() ) def UpperCAmelCase_ ( self : Dict ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Vector([1, 2, 3] ) self.assertEqual("(14,32,50)" , str(a * x ) ) self.assertEqual("|2,4,6|\n|8,10,12|\n|14,16,18|\n" , str(a * 2 ) ) def UpperCAmelCase_ ( self : Tuple ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) a.change_component(0 , 2 , 5 ) self.assertEqual("|1,2,5|\n|2,4,5|\n|6,7,8|\n" , str(UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Any ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) self.assertEqual(7 , a.component(2 , 1 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]] , 3 , 3 ) self.assertEqual("|2,4,10|\n|4,8,10|\n|12,14,18|\n" , str(a + b ) ) def UpperCAmelCase_ ( self : List[Any] ) -> None: __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 3], [2, 4, 5], [6, 7, 8]] , 3 , 3 ) __SCREAMING_SNAKE_CASE = Matrix([[1, 2, 7], [2, 4, 5], [6, 7, 1_0]] , 3 , 3 ) self.assertEqual("|0,0,-4|\n|0,0,0|\n|0,0,-2|\n" , str(a - b ) ) def UpperCAmelCase_ ( self : Optional[int] ) -> None: self.assertEqual( "|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n|0,0,0,0,0|\n" , str(square_zero_matrix(5 ) ) , ) if __name__ == "__main__": unittest.main()
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = sum(lowerCAmelCase_ ) create_state_space_tree(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return result def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' if sum(lowerCAmelCase_ ) > max_sum or (remaining_nums_sum + sum(lowerCAmelCase_ )) < max_sum: return if sum(lowerCAmelCase_ ) == max_sum: result.append(lowerCAmelCase_ ) return for index in range(lowerCAmelCase_ , len(lowerCAmelCase_ ) ): create_state_space_tree( lowerCAmelCase_ , lowerCAmelCase_ , index + 1 , [*path, nums[index]] , lowerCAmelCase_ , remaining_nums_sum - nums[index] , ) a__ : Optional[Any] = [3, 3_4, 4, 1_2, 5, 2] a__ : Dict = 9 a__ : int = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() a__ : Any = logging.get_logger() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = True ): '''simple docstring''' print(f"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __SCREAMING_SNAKE_CASE = timm.create_model("levit_128s" , pretrained=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = timm.create_model("levit_128" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 192: __SCREAMING_SNAKE_CASE = timm.create_model("levit_192" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 256: __SCREAMING_SNAKE_CASE = timm.create_model("levit_256" , pretrained=lowerCAmelCase_ ) if hidden_sizes == 384: __SCREAMING_SNAKE_CASE = timm.create_model("levit_384" , pretrained=lowerCAmelCase_ ) from_model.eval() __SCREAMING_SNAKE_CASE = LevitForImageClassificationWithTeacher(lowerCAmelCase_ ).eval() __SCREAMING_SNAKE_CASE = OrderedDict() __SCREAMING_SNAKE_CASE = from_model.state_dict() __SCREAMING_SNAKE_CASE = list(from_model.state_dict().keys() ) __SCREAMING_SNAKE_CASE = list(our_model.state_dict().keys() ) print(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) for i in range(len(lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = weights[og_keys[i]] our_model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = torch.randn((2, 3, 224, 224) ) __SCREAMING_SNAKE_CASE = from_model(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = our_model(lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ ), "The model logits don't match the original one." __SCREAMING_SNAKE_CASE = name print(lowerCAmelCase_ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __SCREAMING_SNAKE_CASE = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f"""Pushed {checkpoint_name}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = True ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = (1, num_labels) __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = partial(lowerCAmelCase_ , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "levit-128S": 128, "levit-128": 128, "levit-192": 192, "levit-256": 256, "levit-384": 384, } __SCREAMING_SNAKE_CASE = { "levit-128S": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), "levit-128": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), "levit-192": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), "levit-256": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), "levit-384": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , lowerCAmelCase_ , names_to_config[model_name] , lowerCAmelCase_ , lowerCAmelCase_ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return config, expected_shape if __name__ == "__main__": a__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) 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''', ) a__ : str = parser.parse_args() a__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" import requests a__ : List[str] = '''''' # <-- Put your OpenWeatherMap appid here! a__ : str = '''https://api.openweathermap.org/data/2.5/''' def UpperCAmelCase__ (lowerCAmelCase_ = "Chicago" , lowerCAmelCase_ = APPID ): '''simple docstring''' return requests.get(URL_BASE + "weather" , params=locals() ).json() def UpperCAmelCase__ (lowerCAmelCase_ = "Kolkata, India" , lowerCAmelCase_ = APPID ): '''simple docstring''' return requests.get(URL_BASE + "forecast" , params=locals() ).json() def UpperCAmelCase__ (lowerCAmelCase_ = 55.68 , lowerCAmelCase_ = 12.57 , lowerCAmelCase_ = APPID ): '''simple docstring''' return requests.get(URL_BASE + "onecall" , params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: a__ : Any = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" a__ : int = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} a__ : Optional[Any] = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) order.append(lowerCAmelCase_ ) return order def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return component def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) * [False] __SCREAMING_SNAKE_CASE = {vert: [] for vert in range(len(lowerCAmelCase_ ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for i, was_visited in enumerate(lowerCAmelCase_ ): if not was_visited: order += topology_sort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) * [False] for i in range(len(lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = order[len(lowerCAmelCase_ ) - i - 1] if not visited[vert]: __SCREAMING_SNAKE_CASE = find_components(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) components_list.append(lowerCAmelCase_ ) return components_list
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' 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 UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' 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 UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' 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()
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = 2 while True: __SCREAMING_SNAKE_CASE = factor_map.pop(lowerCAmelCase_ , lowerCAmelCase_ ) if factor: __SCREAMING_SNAKE_CASE = factor + prime while x in factor_map: x += factor __SCREAMING_SNAKE_CASE = factor else: __SCREAMING_SNAKE_CASE = prime yield prime prime += 1 def UpperCAmelCase__ (lowerCAmelCase_ = 1E10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = sieve() __SCREAMING_SNAKE_CASE = 1 while True: __SCREAMING_SNAKE_CASE = next(lowerCAmelCase_ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(lowerCAmelCase_ ) n += 2 if __name__ == "__main__": print(solution())
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" import math def UpperCAmelCase__ (lowerCAmelCase_ = 100 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = sum(i * i for i in range(1 , n + 1 ) ) __SCREAMING_SNAKE_CASE = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(F"{solution() = }")
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" from abc import ABC, abstractmethod from typing import List, Optional class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple ) -> Tuple: # test for the above condition self.test() def UpperCAmelCase_ ( self : Any ) -> Any: __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = False while not completed: if counter == 1: self.reset() __SCREAMING_SNAKE_CASE = self.advance() if not self.does_advance(UpperCAmelCase__ ): raise Exception( "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true." ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.update(UpperCAmelCase__ ) 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 UpperCAmelCase_ ( self : str ) -> Union[str, Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int ) -> Any: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> Optional[int]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def UpperCAmelCase_ ( self : List[str] ) -> int: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) @abstractmethod def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Tuple=False ) -> List[Any]: raise NotImplementedError( F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : List[int] ) -> List[str]: super(UpperCAmelCase__ , self ).__init__() if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or len(UpperCAmelCase__ ) == 0: raise ValueError(F"""`token_ids` has to be a non-empty list, but is {token_ids}.""" ) if any((not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) 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}.""" ) __SCREAMING_SNAKE_CASE = token_ids __SCREAMING_SNAKE_CASE = len(self.token_ids ) __SCREAMING_SNAKE_CASE = -1 # the index of the currently fulfilled step __SCREAMING_SNAKE_CASE = False def UpperCAmelCase_ ( self : str ) -> List[str]: if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> Dict: if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(UpperCAmelCase__ )}""" ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError(F"""`token_id` has to be an `int`, but is {token_id} of type {type(UpperCAmelCase__ )}""" ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False if self.does_advance(UpperCAmelCase__ ): self.fulfilled_idx += 1 __SCREAMING_SNAKE_CASE = True if self.fulfilled_idx == (self.seqlen - 1): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = completed else: # failed to make progress. __SCREAMING_SNAKE_CASE = True self.reset() return stepped, completed, reset def UpperCAmelCase_ ( self : List[str] ) -> str: __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = 0 def UpperCAmelCase_ ( self : Tuple ) -> Dict: return self.seqlen - (self.fulfilled_idx + 1) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[str]=False ) -> List[Any]: __SCREAMING_SNAKE_CASE = PhrasalConstraint(self.token_ids ) if stateful: __SCREAMING_SNAKE_CASE = self.seqlen __SCREAMING_SNAKE_CASE = self.fulfilled_idx __SCREAMING_SNAKE_CASE = self.completed return new_constraint class UpperCamelCase_ : """simple docstring""" def __init__( self : int , UpperCAmelCase__ : List[List[int]] , UpperCAmelCase__ : Tuple=True ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max([len(UpperCAmelCase__ ) for one in nested_token_ids] ) __SCREAMING_SNAKE_CASE = {} for token_ids in nested_token_ids: __SCREAMING_SNAKE_CASE = root for tidx, token_id in enumerate(UpperCAmelCase__ ): if token_id not in level: __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = level[token_id] if no_subsets and self.has_subsets(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError( "Each list in `nested_token_ids` can't be a complete subset of another list, but is" F""" {nested_token_ids}.""" ) __SCREAMING_SNAKE_CASE = root def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.trie for current_token in current_seq: __SCREAMING_SNAKE_CASE = start[current_token] __SCREAMING_SNAKE_CASE = list(start.keys() ) return next_tokens def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any ) -> Any: __SCREAMING_SNAKE_CASE = self.next_tokens(UpperCAmelCase__ ) return len(UpperCAmelCase__ ) == 0 def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = list(root.values() ) if len(UpperCAmelCase__ ) == 0: return 1 else: return sum([self.count_leaves(UpperCAmelCase__ ) for nn in next_nodes] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.count_leaves(UpperCAmelCase__ ) return len(UpperCAmelCase__ ) != leaf_count class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : List[List[int]] ) -> Any: super(UpperCAmelCase__ , self ).__init__() if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or len(UpperCAmelCase__ ) == 0: raise ValueError(F"""`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.""" ) if any(not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) 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(UpperCAmelCase__ , UpperCAmelCase__ ) 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}.""" ) __SCREAMING_SNAKE_CASE = DisjunctiveTrie(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = nested_token_ids __SCREAMING_SNAKE_CASE = self.trie.max_height __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = False def UpperCAmelCase_ ( self : List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) if len(UpperCAmelCase__ ) == 0: return None else: return token_list def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : int ) -> List[Any]: if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCAmelCase__ )}""" ) __SCREAMING_SNAKE_CASE = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int ) -> int: if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError(F"""`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCAmelCase__ )}""" ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = False if self.does_advance(UpperCAmelCase__ ): self.current_seq.append(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = True else: __SCREAMING_SNAKE_CASE = True self.reset() __SCREAMING_SNAKE_CASE = self.trie.reached_leaf(self.current_seq ) __SCREAMING_SNAKE_CASE = completed return stepped, completed, reset def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = [] def UpperCAmelCase_ ( self : List[str] ) -> Dict: if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Union[str, Any]=False ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = DisjunctiveConstraint(self.token_ids ) if stateful: __SCREAMING_SNAKE_CASE = self.seqlen __SCREAMING_SNAKE_CASE = self.current_seq __SCREAMING_SNAKE_CASE = self.completed return new_constraint class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : List[Constraint] ) -> Dict: __SCREAMING_SNAKE_CASE = constraints # max # of steps required to fulfill a given constraint __SCREAMING_SNAKE_CASE = max([c.seqlen for c in constraints] ) __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False self.init_state() def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = [constraint.copy(stateful=UpperCAmelCase__ ) for constraint in self.constraints] def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = 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 UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" __SCREAMING_SNAKE_CASE = constraint.advance() if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): token_list.append(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): token_list.extend(UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = self.inprogress_constraint.advance() if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): token_list.append(UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): token_list.extend(UpperCAmelCase__ ) if len(UpperCAmelCase__ ) == 0: return None else: return token_list def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[List[int]] ) -> int: self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.add(UpperCAmelCase__ ) # the entire list of constraints are fulfilled if self.completed: break def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int ) -> Optional[Any]: if not isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError(F"""`token_id` should be an `int`, but is `{token_id}`.""" ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = False, False if self.completed: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = 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 __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.inprogress_constraint.update(UpperCAmelCase__ ) 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=UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = 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 ) __SCREAMING_SNAKE_CASE = None if len(self.pending_constraints ) == 0: # we're done! __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = pending_constraint.update(UpperCAmelCase__ ) 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(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if not complete and stepped: __SCREAMING_SNAKE_CASE = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". __SCREAMING_SNAKE_CASE = ( 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. __SCREAMING_SNAKE_CASE = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str]=True ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: __SCREAMING_SNAKE_CASE = [ constraint.copy(stateful=UpperCAmelCase__ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: __SCREAMING_SNAKE_CASE = self.inprogress_constraint.copy(stateful=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [constraint.copy() for constraint in self.pending_constraints] return new_state
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging a__ : List[Any] = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = ["pixel_values"] def __init__( self : Tuple , UpperCAmelCase__ : bool = True , UpperCAmelCase__ : int = 3_2 , UpperCAmelCase__ : str=PILImageResampling.BILINEAR , UpperCAmelCase__ : bool = True , **UpperCAmelCase__ : Dict , ) -> None: __SCREAMING_SNAKE_CASE = do_resize __SCREAMING_SNAKE_CASE = do_rescale __SCREAMING_SNAKE_CASE = size_divisor __SCREAMING_SNAKE_CASE = resample super().__init__(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Any ) -> np.ndarray: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_image_size(UpperCAmelCase__ ) # Rounds the height and width down to the closest multiple of size_divisor __SCREAMING_SNAKE_CASE = height // size_divisor * size_divisor __SCREAMING_SNAKE_CASE = width // size_divisor * size_divisor __SCREAMING_SNAKE_CASE = resize(UpperCAmelCase__ , (new_h, new_w) , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[ChannelDimension] = None , **UpperCAmelCase__ : Any ) -> np.ndarray: return rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[int]=None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[Union[TensorType, str]] = None , UpperCAmelCase__ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase__ : List[Any] , ) -> BatchFeature: __SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize __SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale __SCREAMING_SNAKE_CASE = size_divisor if size_divisor is not None else self.size_divisor __SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError("size_divisor is required for resizing" ) __SCREAMING_SNAKE_CASE = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError("Invalid image(s)" ) # All transformations expect numpy arrays. __SCREAMING_SNAKE_CASE = [to_numpy_array(UpperCAmelCase__ ) for img in images] if do_resize: __SCREAMING_SNAKE_CASE = [self.resize(UpperCAmelCase__ , size_divisor=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_rescale: __SCREAMING_SNAKE_CASE = [self.rescale(UpperCAmelCase__ , scale=1 / 2_5_5 ) for image in images] __SCREAMING_SNAKE_CASE = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] __SCREAMING_SNAKE_CASE = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , 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 UpperCAmelCase_ ( self : List[Any] ) -> str: 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 UpperCAmelCase_ ( self : List[Any] ) -> List[str]: 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 UpperCAmelCase_ ( self : List[str] ) -> Tuple: 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 UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import warnings from functools import wraps from typing import Callable def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' @wraps(lowerCAmelCase_ ) def _inner_fn(*lowerCAmelCase_ , **lowerCAmelCase_ ): warnings.warn( (f"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future.""") , lowerCAmelCase_ , ) return fn(*lowerCAmelCase_ , **lowerCAmelCase_ ) return _inner_fn
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a__ : Dict = logging.getLogger(__name__) class UpperCamelCase_ : """simple docstring""" def __init__( self : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = False def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : str ) -> List[Any]: if not self.initialized: __SCREAMING_SNAKE_CASE = RagRetriever( UpperCAmelCase__ , question_encoder_tokenizer=UpperCAmelCase__ , generator_tokenizer=UpperCAmelCase__ , index=UpperCAmelCase__ , init_retrieval=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = True def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[int]: self.retriever.index.init_index() def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.retriever._main_retrieve(UpperCAmelCase__ , UpperCAmelCase__ ) return doc_ids, retrieved_doc_embeds class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any=None ) -> str: if index is not None and index.is_initialized() and len(UpperCAmelCase__ ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you'll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( UpperCAmelCase__ , question_encoder_tokenizer=UpperCAmelCase__ , generator_tokenizer=UpperCAmelCase__ , index=UpperCAmelCase__ , init_retrieval=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) for worker in self.retrieval_workers ] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] ) -> Tuple: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __SCREAMING_SNAKE_CASE = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = ray.get(random_worker.retrieve.remote(UpperCAmelCase__ , UpperCAmelCase__ ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._main_retrieve(UpperCAmelCase__ , UpperCAmelCase__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(UpperCAmelCase__ ) @classmethod def UpperCAmelCase_ ( cls : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int=None , **UpperCAmelCase__ : Any ) -> Tuple: return super(UpperCAmelCase__ , cls ).get_tokenizers(UpperCAmelCase__ , UpperCAmelCase__ , **UpperCAmelCase__ ) @classmethod def UpperCAmelCase_ ( cls : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int]=None , **UpperCAmelCase__ : str ) -> Tuple: __SCREAMING_SNAKE_CASE = kwargs.pop("config" , UpperCAmelCase__ ) or RagConfig.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = RagTokenizer.from_pretrained(UpperCAmelCase__ , config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = rag_tokenizer.question_encoder __SCREAMING_SNAKE_CASE = rag_tokenizer.generator if indexed_dataset is not None: __SCREAMING_SNAKE_CASE = "custom" __SCREAMING_SNAKE_CASE = CustomHFIndex(config.retrieval_vector_size , UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = cls._build_index(UpperCAmelCase__ ) return cls( UpperCAmelCase__ , question_encoder_tokenizer=UpperCAmelCase__ , generator_tokenizer=UpperCAmelCase__ , retrieval_workers=UpperCAmelCase__ , index=UpperCAmelCase__ , )
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel a__ : str = '''0.12''' # assumed parallelism: 8 @require_flax @is_staging_test class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @classmethod def UpperCAmelCase_ ( cls : Dict ) -> Any: __SCREAMING_SNAKE_CASE = TOKEN HfFolder.save_token(UpperCAmelCase__ ) @classmethod def UpperCAmelCase_ ( cls : Any ) -> Any: try: delete_repo(token=cls._token , repo_id="test-model-flax" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org" ) except HTTPError: pass def UpperCAmelCase_ ( self : List[str] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) __SCREAMING_SNAKE_CASE = FlaxBertModel(UpperCAmelCase__ ) model.push_to_hub("test-model-flax" , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""" ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(UpperCAmelCase__ , 1E-3 , msg=F"""{key} not identical""" ) # Reset repo delete_repo(token=self._token , repo_id="test-model-flax" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(UpperCAmelCase__ , repo_id="test-model-flax" , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(F"""{USER}/test-model-flax""" ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(UpperCAmelCase__ , 1E-3 , msg=F"""{key} not identical""" ) def UpperCAmelCase_ ( self : Any ) -> str: __SCREAMING_SNAKE_CASE = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) __SCREAMING_SNAKE_CASE = FlaxBertModel(UpperCAmelCase__ ) model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(UpperCAmelCase__ , 1E-3 , msg=F"""{key} not identical""" ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( UpperCAmelCase__ , repo_id="valid_org/test-model-flax-org" , push_to_hub=UpperCAmelCase__ , use_auth_token=self._token ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(model.params ) ) __SCREAMING_SNAKE_CASE = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): __SCREAMING_SNAKE_CASE = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(UpperCAmelCase__ , 1E-3 , msg=F"""{key} not identical""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = flatten_dict(modela.params ) __SCREAMING_SNAKE_CASE = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: __SCREAMING_SNAKE_CASE = False return models_are_equal @require_flax class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] ) -> int: __SCREAMING_SNAKE_CASE = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) __SCREAMING_SNAKE_CASE = FlaxBertModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) ) with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.assertTrue(check_models_equal(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : List[Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) __SCREAMING_SNAKE_CASE = FlaxBertModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) , max_shard_size="10KB" ) with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.assertTrue(check_models_equal(UpperCAmelCase__ , UpperCAmelCase__ ) ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = "bert" __SCREAMING_SNAKE_CASE = "hf-internal-testing/tiny-random-bert-subfolder" with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> int: __SCREAMING_SNAKE_CASE = "bert" __SCREAMING_SNAKE_CASE = "hf-internal-testing/tiny-random-bert-sharded-subfolder" with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = FlaxBertModel.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ )
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return 1.0 / (1.0 + np.exp(-_outputs )) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(_outputs , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "sigmoid" snake_case__ : List[str] = "softmax" snake_case__ : Optional[Any] = "none" @add_end_docstrings( UpperCamelCase , R"\n return_all_scores (`bool`, *optional*, defaults to `False`):\n Whether to return all prediction scores or just the one of the predicted class.\n function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n has several labels, will apply the softmax function on the output.\n - `\"sigmoid\"`: Applies the sigmoid function on the output.\n - `\"softmax\"`: Applies the softmax function on the output.\n - `\"none\"`: Does not apply any function on the output.\n " , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = False snake_case__ : Optional[Any] = ClassificationFunction.NONE def __init__( self : Any , **UpperCAmelCase__ : Union[str, Any] ) -> Union[str, Any]: super().__init__(**UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == "tf" else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Dict="" , **UpperCAmelCase__ : List[Any] ) -> Dict: # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" __SCREAMING_SNAKE_CASE = tokenizer_kwargs __SCREAMING_SNAKE_CASE = {} if hasattr(self.model.config , "return_all_scores" ) and return_all_scores is None: __SCREAMING_SNAKE_CASE = self.model.config.return_all_scores if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) or top_k is None: __SCREAMING_SNAKE_CASE = top_k __SCREAMING_SNAKE_CASE = False elif return_all_scores is not None: warnings.warn( "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`." , UpperCAmelCase__ , ) if return_all_scores: __SCREAMING_SNAKE_CASE = None else: __SCREAMING_SNAKE_CASE = 1 if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: __SCREAMING_SNAKE_CASE = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : Any , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. __SCREAMING_SNAKE_CASE = "top_k" not in kwargs if isinstance(args[0] , UpperCAmelCase__ ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , **UpperCAmelCase__ : Tuple ) -> Dict[str, GenericTensor]: __SCREAMING_SNAKE_CASE = self.framework if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return self.tokenizer(**UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and len(UpperCAmelCase__ ) == 1 and isinstance(inputs[0] , UpperCAmelCase__ ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair." ) return self.tokenizer(UpperCAmelCase__ , return_tensors=UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Any ) -> Optional[int]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : List[Any]=1 , UpperCAmelCase__ : int=True ) -> str: # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: __SCREAMING_SNAKE_CASE = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: __SCREAMING_SNAKE_CASE = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , "function_to_apply" ) and function_to_apply is None: __SCREAMING_SNAKE_CASE = self.model.config.function_to_apply else: __SCREAMING_SNAKE_CASE = ClassificationFunction.NONE __SCREAMING_SNAKE_CASE = model_outputs["logits"][0] __SCREAMING_SNAKE_CASE = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: __SCREAMING_SNAKE_CASE = sigmoid(UpperCAmelCase__ ) elif function_to_apply == ClassificationFunction.SOFTMAX: __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) elif function_to_apply == ClassificationFunction.NONE: __SCREAMING_SNAKE_CASE = outputs else: raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}""" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} __SCREAMING_SNAKE_CASE = [ {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(UpperCAmelCase__ ) ] if not _legacy: dict_scores.sort(key=lambda UpperCAmelCase__ : x["score"] , reverse=UpperCAmelCase__ ) if top_k is not None: __SCREAMING_SNAKE_CASE = dict_scores[:top_k] return dict_scores
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" from math import asin, atan, cos, radians, sin, sqrt, tan a__ : Dict = 6_37_81_37.0 a__ : Optional[int] = 6_35_67_52.31_42_45 a__ : Optional[int] = 6_3_7_8_1_3_7 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = (AXIS_A - AXIS_B) / AXIS_A __SCREAMING_SNAKE_CASE = atan((1 - flattening) * tan(radians(lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = atan((1 - flattening) * tan(radians(lowerCAmelCase_ ) ) ) __SCREAMING_SNAKE_CASE = radians(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = radians(lowerCAmelCase_ ) # Equation __SCREAMING_SNAKE_CASE = sin((phi_a - phi_a) / 2 ) __SCREAMING_SNAKE_CASE = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda __SCREAMING_SNAKE_CASE = sqrt(sin_sq_phi + (cos(lowerCAmelCase_ ) * cos(lowerCAmelCase_ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __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 = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" import math from collections.abc import Callable def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = xa __SCREAMING_SNAKE_CASE = xa while True: if x_n == x_na or function(lowerCAmelCase_ ) == function(lowerCAmelCase_ ): raise ZeroDivisionError("float division by zero, could not find root" ) __SCREAMING_SNAKE_CASE = x_na - ( function(lowerCAmelCase_ ) / ((function(lowerCAmelCase_ ) - function(lowerCAmelCase_ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na __SCREAMING_SNAKE_CASE = x_na __SCREAMING_SNAKE_CASE = x_na def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return math.pow(lowerCAmelCase_ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any]=1_3 , UpperCAmelCase__ : List[Any]=7 , UpperCAmelCase__ : int=True , UpperCAmelCase__ : int=True , UpperCAmelCase__ : List[Any]=True , UpperCAmelCase__ : Dict=True , UpperCAmelCase__ : Any=9_9 , UpperCAmelCase__ : Any=3_2 , UpperCAmelCase__ : Optional[Any]=5 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Dict=3_7 , UpperCAmelCase__ : str="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Union[str, Any]=5_1_2 , UpperCAmelCase__ : str=1_6 , UpperCAmelCase__ : List[Any]=2 , UpperCAmelCase__ : Dict=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Union[str, Any]=4 , UpperCAmelCase__ : Dict=None , ) -> List[str]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[Any]: return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = NystromformerModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = NystromformerForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = NystromformerForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NystromformerForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NystromformerForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NystromformerForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : str ) -> int: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Any = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NystromformerModel, "fill-mask": NystromformerForMaskedLM, "question-answering": NystromformerForQuestionAnswering, "text-classification": NystromformerForSequenceClassification, "token-classification": NystromformerForTokenClassification, "zero-shot": NystromformerForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Union[str, Any] = False snake_case__ : Union[str, Any] = False def UpperCAmelCase_ ( self : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NystromformerModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> str: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NystromformerModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = NystromformerModel.from_pretrained("uw-madison/nystromformer-512" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.4_532, -0.0_936, 0.5_137], [-0.2_676, 0.0_628, 0.6_186], [-0.3_629, -0.1_726, 0.4_716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = "the [MASK] of Belgium is Brussels" __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("uw-madison/nystromformer-512" ) __SCREAMING_SNAKE_CASE = NystromformerForMaskedLM.from_pretrained("uw-madison/nystromformer-512" ) __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(encoding.input_ids ).logits __SCREAMING_SNAKE_CASE = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(UpperCAmelCase__ ) , "capital" )
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" from typing import Dict, List, Optional from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : str = { '''nielsr/canine-s''': 2_0_4_8, } # Unicode defines 1,114,112 total “codepoints” a__ : str = 1_1_1_4_1_1_2 # Below: Constants defining canonical codepoints for special, pseudo-characters. # Copied from https://github.com/google-research/language/blob/master/language/canine/special_codepoints.py a__ : Dict = 0 a__ : Union[str, Any] = 0XE000 a__ : int = 0XE001 a__ : Tuple = 0XE002 a__ : int = 0XE003 a__ : str = 0XE004 # Maps special codepoints to human-readable names. a__ : Dict[int, str] = { # Special symbols are represented using codepoints values that are valid, # but designated as "Private Use", meaning that they will never be assigned # characters by the Unicode Consortium, and are thus safe for use here. # # NOTE: Do *NOT* add any sort of [UNK_CHAR] here. They are explicitly # excluded and should fail with a hard error. CLS: "[CLS]", SEP: "[SEP]", BOS: "[BOS]", MASK: "[MASK]", PAD: "[PAD]", RESERVED: "[RESERVED]", } # Maps special codepoint human-readable names to their codepoint values. a__ : Dict[str, int] = {name: codepoint for codepoint, name in SPECIAL_CODEPOINTS.items()} class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : Dict , UpperCAmelCase__ : str=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : Tuple=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : Dict=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : str=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : Optional[Any]=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : Dict=chr(UpperCAmelCase__ ) , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Union[str, Any]=2_0_4_8 , **UpperCAmelCase__ : Optional[int] , ) -> Tuple: __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else bos_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else eos_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else sep_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else cls_token __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it __SCREAMING_SNAKE_CASE = AddedToken(UpperCAmelCase__ , lstrip=UpperCAmelCase__ , rstrip=UpperCAmelCase__ ) if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else mask_token super().__init__( bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , model_max_length=UpperCAmelCase__ , **UpperCAmelCase__ , ) # Creates a mapping for looking up the IDs of special symbols. __SCREAMING_SNAKE_CASE = {} for codepoint, name in SPECIAL_CODEPOINTS.items(): __SCREAMING_SNAKE_CASE = codepoint # Creates a mapping for looking up the string forms of special symbol IDs. __SCREAMING_SNAKE_CASE = { codepoint: name for name, codepoint in self._special_codepoints.items() } __SCREAMING_SNAKE_CASE = UNICODE_VOCAB_SIZE __SCREAMING_SNAKE_CASE = len(self._special_codepoints ) @property def UpperCAmelCase_ ( self : Any ) -> int: return self._unicode_vocab_size def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str ) -> List[str]: return list(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str ) -> int: try: return ord(UpperCAmelCase__ ) except TypeError: raise ValueError(F"""invalid token: '{token}'""" ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : int ) -> str: try: if index in SPECIAL_CODEPOINTS: return SPECIAL_CODEPOINTS[index] return chr(UpperCAmelCase__ ) except TypeError: raise ValueError(F"""invalid id: {index}""" ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Dict ) -> Union[str, Any]: return "".join(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] __SCREAMING_SNAKE_CASE = cls + token_ids_a + sep if token_ids_a is not None: result += token_ids_a + sep return result def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None , UpperCAmelCase__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCAmelCase__ , token_ids_a=UpperCAmelCase__ , already_has_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [1] + ([0] * len(UpperCAmelCase__ )) + [1] if token_ids_a is not None: result += ([0] * len(UpperCAmelCase__ )) + [1] return result def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] __SCREAMING_SNAKE_CASE = len(cls + token_ids_a + sep ) * [0] if token_ids_a is not None: result += len(token_ids_a + sep ) * [1] return result def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Union[str, Any]: return ()
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "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, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() a__ : List[Any] = logging.get_logger('''transformers.models.speecht5''') def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' hf_model.apply_weight_norm() __SCREAMING_SNAKE_CASE = checkpoint["input_conv.weight_g"] __SCREAMING_SNAKE_CASE = checkpoint["input_conv.weight_v"] __SCREAMING_SNAKE_CASE = checkpoint["input_conv.bias"] for i in range(len(config.upsample_rates ) ): __SCREAMING_SNAKE_CASE = checkpoint[f"""upsamples.{i}.1.weight_g"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""upsamples.{i}.1.weight_v"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""upsamples.{i}.1.bias"""] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_g"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs1.{j}.1.weight_v"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs1.{j}.1.bias"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_g"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs2.{j}.1.weight_v"""] __SCREAMING_SNAKE_CASE = checkpoint[f"""blocks.{i}.convs2.{j}.1.bias"""] __SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.weight_g"] __SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.weight_v"] __SCREAMING_SNAKE_CASE = checkpoint["output_conv.1.bias"] hf_model.remove_weight_norm() @torch.no_grad() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ): '''simple docstring''' if config_path is not None: __SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig.from_pretrained(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = SpeechTaHifiGanConfig() __SCREAMING_SNAKE_CASE = SpeechTaHifiGan(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = torch.load(lowerCAmelCase_ ) load_weights(orig_checkpoint["model"]["generator"] , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.load(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = stats[0].reshape(-1 ) __SCREAMING_SNAKE_CASE = stats[1].reshape(-1 ) __SCREAMING_SNAKE_CASE = torch.from_numpy(lowerCAmelCase_ ).float() __SCREAMING_SNAKE_CASE = torch.from_numpy(lowerCAmelCase_ ).float() model.save_pretrained(lowerCAmelCase_ ) if repo_id: print("Pushing to the hub..." ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--stats_path''', required=True, default=None, type=str, help='''Path to stats.npy file''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) a__ : Any = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" from typing import Dict, Optional import numpy as np import datasets a__ : Optional[int] = ''' IoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union between the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation, the mean IoU of the image is calculated by taking the IoU of each class and averaging them. ''' a__ : Union[str, Any] = ''' Args: predictions (`List[ndarray]`): List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. references (`List[ndarray]`): List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size. num_labels (`int`): Number of classes (categories). ignore_index (`int`): Index that will be ignored during evaluation. nan_to_num (`int`, *optional*): If specified, NaN values will be replaced by the number defined by the user. label_map (`dict`, *optional*): If specified, dictionary mapping old label indices to new label indices. reduce_labels (`bool`, *optional*, defaults to `False`): Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255. Returns: `Dict[str, float | ndarray]` comprising various elements: - *mean_iou* (`float`): Mean Intersection-over-Union (IoU averaged over all categories). - *mean_accuracy* (`float`): Mean accuracy (averaged over all categories). - *overall_accuracy* (`float`): Overall accuracy on all images. - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`): Per category accuracy. - *per_category_iou* (`ndarray` of shape `(num_labels,)`): Per category IoU. Examples: >>> import numpy as np >>> mean_iou = datasets.load_metric("mean_iou") >>> # suppose one has 3 different segmentation maps predicted >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]]) >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]]) >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]]) >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]]) >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]]) >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]]) >>> predicted = [predicted_1, predicted_2, predicted_3] >>> ground_truth = [actual_1, actual_2, actual_3] >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False) >>> print(results) # doctest: +NORMALIZE_WHITESPACE {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])} ''' a__ : Any = '''\ @software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020, author = {{MMSegmentation Contributors}}, license = {Apache-2.0}, month = {7}, title = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}}, url = {https://github.com/open-mmlab/mmsegmentation}, year = {2020} }''' def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , ): '''simple docstring''' if label_map is not None: for old_id, new_id in label_map.items(): __SCREAMING_SNAKE_CASE = new_id # turn into Numpy arrays __SCREAMING_SNAKE_CASE = np.array(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.array(lowerCAmelCase_ ) if reduce_labels: __SCREAMING_SNAKE_CASE = 255 __SCREAMING_SNAKE_CASE = label - 1 __SCREAMING_SNAKE_CASE = 255 __SCREAMING_SNAKE_CASE = label != ignore_index __SCREAMING_SNAKE_CASE = np.not_equal(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = pred_label[mask] __SCREAMING_SNAKE_CASE = np.array(lowerCAmelCase_ )[mask] __SCREAMING_SNAKE_CASE = pred_label[pred_label == label] __SCREAMING_SNAKE_CASE = np.histogram(lowerCAmelCase_ , bins=lowerCAmelCase_ , range=(0, num_labels - 1) )[0] __SCREAMING_SNAKE_CASE = np.histogram(lowerCAmelCase_ , bins=lowerCAmelCase_ , range=(0, num_labels - 1) )[0] __SCREAMING_SNAKE_CASE = np.histogram(lowerCAmelCase_ , bins=lowerCAmelCase_ , range=(0, num_labels - 1) )[0] __SCREAMING_SNAKE_CASE = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.zeros((num_labels,) , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = np.zeros((num_labels,) , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = np.zeros((num_labels,) , dtype=np.floataa ) __SCREAMING_SNAKE_CASE = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = intersect_and_union( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = total_intersect_and_union( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # compute metrics __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = total_area_intersect.sum() / total_area_label.sum() __SCREAMING_SNAKE_CASE = total_area_intersect / total_area_union __SCREAMING_SNAKE_CASE = total_area_intersect / total_area_label __SCREAMING_SNAKE_CASE = np.nanmean(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.nanmean(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = all_acc __SCREAMING_SNAKE_CASE = iou __SCREAMING_SNAKE_CASE = acc if nan_to_num is not None: __SCREAMING_SNAKE_CASE = {metric: np.nan_to_num(lowerCAmelCase_ , nan=lowerCAmelCase_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : str ) -> List[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) , reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] , ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : bool , UpperCAmelCase__ : Optional[int] = None , UpperCAmelCase__ : Optional[Dict[int, int]] = None , UpperCAmelCase__ : bool = False , ) -> Dict: __SCREAMING_SNAKE_CASE = mean_iou( results=UpperCAmelCase__ , gt_seg_maps=UpperCAmelCase__ , num_labels=UpperCAmelCase__ , ignore_index=UpperCAmelCase__ , nan_to_num=UpperCAmelCase__ , label_map=UpperCAmelCase__ , reduce_labels=UpperCAmelCase__ , ) return iou_result
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) a__ : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''', '''UniSpeechForCTC''', '''UniSpeechForPreTraining''', '''UniSpeechForSequenceClassification''', '''UniSpeechModel''', '''UniSpeechPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys a__ : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations import math def UpperCAmelCase__ (lowerCAmelCase_ ): '''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(lowerCAmelCase_ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [n] for i in range(1 , len(lowerCAmelCase_ ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if len(str(lowerCAmelCase_ ) ) > 3: if not is_prime(int(str(lowerCAmelCase_ )[-3:] ) ) or not is_prime(int(str(lowerCAmelCase_ )[:3] ) ): return False return True def UpperCAmelCase__ (lowerCAmelCase_ = 11 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = 13 while len(lowerCAmelCase_ ) != count: if validate(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = list_truncated_nums(lowerCAmelCase_ ) if all(is_prime(lowerCAmelCase_ ) for i in list_nums ): list_truncated_primes.append(lowerCAmelCase_ ) num += 2 return list_truncated_primes def UpperCAmelCase__ (): '''simple docstring''' return sum(compute_truncated_primes(11 ) ) if __name__ == "__main__": print(F"{sum(compute_truncated_primes(1_1)) = }")
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if collection == []: return [] # get some information about the collection __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ ) # create the counting array __SCREAMING_SNAKE_CASE = coll_max + 1 - coll_min __SCREAMING_SNAKE_CASE = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = counting_arr[i] + counting_arr[i - 1] # create the output collection __SCREAMING_SNAKE_CASE = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , lowerCAmelCase_ ) ): __SCREAMING_SNAKE_CASE = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return "".join([chr(lowerCAmelCase_ ) for i in counting_sort([ord(lowerCAmelCase_ ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string('''thisisthestring''') == "eghhiiinrsssttt" a__ : Dict = input('''Enter numbers separated by a comma:\n''').strip() a__ : Optional[Any] = [int(item) for item in user_input.split(''',''')] print(counting_sort(unsorted))
682
1
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> Dict: __SCREAMING_SNAKE_CASE = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "的", "价", "格", "是", "15", "便", "alex", "##andra", ",", "。", "-", "t", "shirt", ] __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] ) ) __SCREAMING_SNAKE_CASE = { "do_resize": True, "size": {"height": 2_2_4, "width": 2_2_4}, "do_center_crop": True, "crop_size": {"height": 1_8, "width": 1_8}, "do_normalize": True, "image_mean": [0.48_145_466, 0.4_578_275, 0.40_821_073], "image_std": [0.26_862_954, 0.26_130_258, 0.27_577_711], "do_convert_rgb": True, } __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , UpperCAmelCase__ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , **UpperCAmelCase__ : Union[str, Any] ) -> Tuple: return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[str] , **UpperCAmelCase__ : List[str] ) -> Dict: return BertTokenizerFast.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase_ ( self : Dict ) -> str: __SCREAMING_SNAKE_CASE = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE = [Image.fromarray(np.moveaxis(UpperCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , UpperCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , UpperCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> str: __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE = self.get_tokenizer(cls_token="(CLS)" , sep_token="(SEP)" ) __SCREAMING_SNAKE_CASE = self.get_image_processor(do_normalize=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="(CLS)" , sep_token="(SEP)" , do_normalize=UpperCAmelCase__ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = image_processor(UpperCAmelCase__ , return_tensors="np" ) __SCREAMING_SNAKE_CASE = processor(images=UpperCAmelCase__ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def UpperCAmelCase_ ( self : str ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "Alexandra,T-shirt的价格是15便士。" __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "Alexandra,T-shirt的价格是15便士。" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with pytest.raises(UpperCAmelCase__ ): processor() def UpperCAmelCase_ ( self : Any ) -> str: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE = processor.batch_decode(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.get_image_processor() __SCREAMING_SNAKE_CASE = self.get_tokenizer() __SCREAMING_SNAKE_CASE = ChineseCLIPProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = "Alexandra,T-shirt的价格是15便士。" __SCREAMING_SNAKE_CASE = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
682
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a__ : Tuple = { '''configuration_rag''': ['''RagConfig'''], '''retrieval_rag''': ['''RagRetriever'''], '''tokenization_rag''': ['''RagTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''RagModel''', '''RagPreTrainedModel''', '''RagSequenceForGeneration''', '''RagTokenForGeneration''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : int = [ '''TFRagModel''', '''TFRagPreTrainedModel''', '''TFRagSequenceForGeneration''', '''TFRagTokenForGeneration''', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys a__ : Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
1
"""simple docstring""" import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if (ksize % 2) == 0: __SCREAMING_SNAKE_CASE = ksize + 1 __SCREAMING_SNAKE_CASE = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(lowerCAmelCase_ ): for x in range(lowerCAmelCase_ ): # distance from center __SCREAMING_SNAKE_CASE = x - ksize // 2 __SCREAMING_SNAKE_CASE = y - ksize // 2 # degree to radiant __SCREAMING_SNAKE_CASE = theta / 180 * np.pi __SCREAMING_SNAKE_CASE = np.cos(_theta ) __SCREAMING_SNAKE_CASE = np.sin(_theta ) # get kernel x __SCREAMING_SNAKE_CASE = cos_theta * px + sin_theta * py # get kernel y __SCREAMING_SNAKE_CASE = -sin_theta * px + cos_theta * py # fill kernel __SCREAMING_SNAKE_CASE = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image a__ : Tuple = imread('''../image_data/lena.jpg''') # turn image in gray scale value a__ : Any = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges a__ : int = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: a__ : str = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) a__ : Tuple = out / out.max() * 2_5_5 a__ : Any = out.astype(np.uinta) imshow('''Original''', gray) imshow('''Gabor filter with 20x20 mask and 6 directions''', out) waitKey(0)
682
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/config.json''', '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/config.json''', '''xlm-roberta-large-finetuned-conll02-dutch''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll02-spanish''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-english''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json''' ), '''xlm-roberta-large-finetuned-conll03-german''': ( '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json''' ), } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Any = "xlm-roberta" def __init__( self : int , UpperCAmelCase__ : Union[str, Any]=3_0_5_2_2 , UpperCAmelCase__ : Optional[Any]=7_6_8 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : str=3_0_7_2 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : Any=0.1 , UpperCAmelCase__ : Optional[int]=5_1_2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : int=0.02 , UpperCAmelCase__ : Optional[int]=1E-12 , UpperCAmelCase__ : Any=1 , UpperCAmelCase__ : Any=0 , UpperCAmelCase__ : str=2 , UpperCAmelCase__ : Any="absolute" , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : int , ) -> Tuple: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = position_embedding_type __SCREAMING_SNAKE_CASE = use_cache __SCREAMING_SNAKE_CASE = classifier_dropout class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @property def UpperCAmelCase_ ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
682
1
"""simple docstring""" a__ : Optional[int] = '''Alexander Joslin''' import operator as op from .stack import Stack def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __SCREAMING_SNAKE_CASE = Stack() __SCREAMING_SNAKE_CASE = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowerCAmelCase_ ) ) elif i in operators: # RULE 2 operator_stack.push(lowerCAmelCase_ ) elif i == ")": # RULE 4 __SCREAMING_SNAKE_CASE = operator_stack.peek() operator_stack.pop() __SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() __SCREAMING_SNAKE_CASE = operand_stack.peek() operand_stack.pop() __SCREAMING_SNAKE_CASE = operators[opr](lowerCAmelCase_ , lowerCAmelCase_ ) operand_stack.push(lowerCAmelCase_ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": a__ : List[str] = '''(5 + ((4 * 2) * (2 + 3)))''' # answer = 45 print(F"{equation} = {dijkstras_two_stack_algorithm(equation)}")
682
"""simple docstring""" import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = checkpoints.load_tax_checkpoint(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flatten_dict(lowerCAmelCase_ ) return flax_params def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = { "token_embedder": "embeddings", "encoder_norm": "layernorm", "kernel": "weight", ".out": ".output", "scale": "weight", "embedders_0.pos_embedding": "row_embedder.weight", "embedders_1.pos_embedding": "column_embedder.weight", } __SCREAMING_SNAKE_CASE = { "query": "attention.query", "key": "attention.key", "value": "attention.value", "output.dense": "output", "encoder_decoder_attention.o": "encoder_decoder_attention.attention.o", "pre_self_attention_layer_norm": "self_attention.layer_norm", "pre_cross_attention_layer_norm": "encoder_decoder_attention.layer_norm", "mlp.": "mlp.DenseReluDense.", "pre_mlp_layer_norm": "mlp.layer_norm", "self_attention.o": "self_attention.attention.o", "decoder.embeddings.embedding": "decoder.embed_tokens.weight", "decoder.relpos_bias.rel_embedding": "decoder.layer.0.self_attention.attention.relative_attention_bias.weight", "decoder.decoder_norm.weight": "decoder.final_layer_norm.weight", "decoder.logits_dense.weight": "decoder.lm_head.weight", } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __SCREAMING_SNAKE_CASE = ".".join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __SCREAMING_SNAKE_CASE = new_key.replace(lowerCAmelCase_ , lowerCAmelCase_ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = new_key.replace("encoder" , "encoder.encoder" ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __SCREAMING_SNAKE_CASE = re.sub(R"layers_(\d+)" , R"layer.\1" , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = flax_dict[key] __SCREAMING_SNAKE_CASE = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key].T ) else: __SCREAMING_SNAKE_CASE = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_flax_param(lowerCAmelCase_ ) if not use_large: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig() __SCREAMING_SNAKE_CASE = PixaStructTextConfig() else: __SCREAMING_SNAKE_CASE = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) __SCREAMING_SNAKE_CASE = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = PixaStructForConditionalGeneration(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = rename_and_convert_flax_params(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("ybelkada/test-pix2struct-tokenizer" ) __SCREAMING_SNAKE_CASE = PixaStructImageProcessor() __SCREAMING_SNAKE_CASE = PixaStructProcessor(image_processor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) if use_large: __SCREAMING_SNAKE_CASE = 4096 __SCREAMING_SNAKE_CASE = True # mkdir if needed os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) print("Model saved in {}".format(lowerCAmelCase_ ) ) if __name__ == "__main__": a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument('''--t5x_checkpoint_path''', default=None, type=str, help='''Path to the original T5x checkpoint.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--use_large''', action='''store_true''', help='''Use large model.''') parser.add_argument('''--is_vqa''', action='''store_true''', help='''Use large model.''') a__ : Optional[Any] = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
682
1
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
1
"""simple docstring""" import argparse import tensorflow as tf import torch from transformers import BertConfig, BertForMaskedLM from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertPooler, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging logging.set_verbosity_info() def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' def get_masked_lm_array(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE""" __SCREAMING_SNAKE_CASE = tf.train.load_variable(lowerCAmelCase_ , lowerCAmelCase_ ) if "kernel" in name: __SCREAMING_SNAKE_CASE = array.transpose() return torch.from_numpy(lowerCAmelCase_ ) def get_encoder_array(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE""" __SCREAMING_SNAKE_CASE = tf.train.load_variable(lowerCAmelCase_ , lowerCAmelCase_ ) if "kernel" in name: __SCREAMING_SNAKE_CASE = array.transpose() return torch.from_numpy(lowerCAmelCase_ ) def get_encoder_layer_array(lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE""" __SCREAMING_SNAKE_CASE = tf.train.load_variable(lowerCAmelCase_ , lowerCAmelCase_ ) if "kernel" in name: __SCREAMING_SNAKE_CASE = array.transpose() return torch.from_numpy(lowerCAmelCase_ ) def get_encoder_attention_layer_array(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = f"""encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE""" __SCREAMING_SNAKE_CASE = tf.train.load_variable(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = array.reshape(lowerCAmelCase_ ) if "kernel" in name: __SCREAMING_SNAKE_CASE = array.transpose() return torch.from_numpy(lowerCAmelCase_ ) print(f"""Loading model based on config from {config_path}...""" ) __SCREAMING_SNAKE_CASE = BertConfig.from_json_file(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = BertForMaskedLM(lowerCAmelCase_ ) # Layers for layer_index in range(0 , config.num_hidden_layers ): __SCREAMING_SNAKE_CASE = model.bert.encoder.layer[layer_index] # Self-attention __SCREAMING_SNAKE_CASE = layer.attention.self __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_query_dense/kernel" , self_attn.query.weight.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_query_dense/bias" , self_attn.query.bias.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_key_dense/kernel" , self_attn.key.weight.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_key_dense/bias" , self_attn.key.bias.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_value_dense/kernel" , self_attn.value.weight.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_value_dense/bias" , self_attn.value.bias.data.shape ) # Self-attention Output __SCREAMING_SNAKE_CASE = layer.attention.output __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_output_dense/kernel" , self_output.dense.weight.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_attention_layer_array( lowerCAmelCase_ , "_output_dense/bias" , self_output.dense.bias.data.shape ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_attention_layer_norm/gamma" ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_attention_layer_norm/beta" ) # Intermediate __SCREAMING_SNAKE_CASE = layer.intermediate __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_intermediate_dense/kernel" ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_intermediate_dense/bias" ) # Output __SCREAMING_SNAKE_CASE = layer.output __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_output_dense/kernel" ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_output_dense/bias" ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_output_layer_norm/gamma" ) __SCREAMING_SNAKE_CASE = get_encoder_layer_array(lowerCAmelCase_ , "_output_layer_norm/beta" ) # Embeddings __SCREAMING_SNAKE_CASE = get_encoder_array("_position_embedding_layer/embeddings" ) __SCREAMING_SNAKE_CASE = get_encoder_array("_type_embedding_layer/embeddings" ) __SCREAMING_SNAKE_CASE = get_encoder_array("_embedding_norm_layer/gamma" ) __SCREAMING_SNAKE_CASE = get_encoder_array("_embedding_norm_layer/beta" ) # LM Head __SCREAMING_SNAKE_CASE = model.cls.predictions.transform __SCREAMING_SNAKE_CASE = get_masked_lm_array("dense/kernel" ) __SCREAMING_SNAKE_CASE = get_masked_lm_array("dense/bias" ) __SCREAMING_SNAKE_CASE = get_masked_lm_array("layer_norm/gamma" ) __SCREAMING_SNAKE_CASE = get_masked_lm_array("layer_norm/beta" ) __SCREAMING_SNAKE_CASE = get_masked_lm_array("embedding_table" ) # Pooling __SCREAMING_SNAKE_CASE = BertPooler(config=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = get_encoder_array("_pooler_layer/kernel" ) __SCREAMING_SNAKE_CASE = get_encoder_array("_pooler_layer/bias" ) # Export final model model.save_pretrained(lowerCAmelCase_ ) # Integration test - should load without any errors ;) __SCREAMING_SNAKE_CASE = BertForMaskedLM.from_pretrained(lowerCAmelCase_ ) print(new_model.eval() ) print("Model conversion was done sucessfully!" ) if __name__ == "__main__": a__ : List[Any] = argparse.ArgumentParser() parser.add_argument( '''--tf_checkpoint_path''', type=str, required=True, help='''Path to the TensorFlow Token Dropping checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', type=str, required=True, help='''The config json file corresponding to the BERT model. This specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', type=str, required=True, help='''Path to the output PyTorch model.''', ) a__ : Tuple = parser.parse_args() convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
682
"""simple docstring""" from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig a__ : Dict = logging.get_logger(__name__) # General docstring a__ : str = '''RegNetConfig''' # Base docstring a__ : List[str] = '''facebook/regnet-y-040''' a__ : int = [1, 1_0_8_8, 7, 7] # Image classification docstring a__ : int = '''facebook/regnet-y-040''' a__ : str = '''tabby, tabby cat''' a__ : Optional[Any] = [ '''facebook/regnet-y-040''', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 3 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : int = 1 , UpperCAmelCase__ : Optional[str] = "relu" , **UpperCAmelCase__ : Tuple , ) -> Any: super().__init__(**UpperCAmelCase__ ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __SCREAMING_SNAKE_CASE = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=UpperCAmelCase__ , strides=UpperCAmelCase__ , padding="VALID" , groups=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" , ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) __SCREAMING_SNAKE_CASE = ACTaFN[activation] if activation is not None else tf.identity def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Optional[int] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.convolution(self.padding(UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = self.normalization(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[Any] , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Optional[Any] ) -> List[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_channels __SCREAMING_SNAKE_CASE = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name="embedder" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = shape_list(UpperCAmelCase__ )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 2, 3, 1) ) __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.ConvaD( filters=UpperCAmelCase__ , kernel_size=1 , strides=UpperCAmelCase__ , use_bias=UpperCAmelCase__ , name="convolution" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name="normalization" ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False ) -> tf.Tensor: return self.normalization(self.convolution(UpperCAmelCase__ ) , training=UpperCAmelCase__ ) class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) __SCREAMING_SNAKE_CASE = [ tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="relu" , name="attention.0" ), tf.keras.layers.ConvaD(filters=UpperCAmelCase__ , kernel_size=1 , activation="sigmoid" , name="attention.2" ), ] def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> Any: # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) for layer_module in self.attention: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = hidden_state * pooled return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Dict , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : int ) -> str: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.2" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : str ) -> Any: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : List[str] , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 1 , **UpperCAmelCase__ : List[Any] ) -> Any: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = in_channels != out_channels or stride != 1 __SCREAMING_SNAKE_CASE = max(1 , out_channels // config.groups_width ) __SCREAMING_SNAKE_CASE = ( TFRegNetShortCut(UpperCAmelCase__ , stride=UpperCAmelCase__ , name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" , name="shortcut" ) ) __SCREAMING_SNAKE_CASE = [ TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=config.hidden_act , name="layer.0" ), TFRegNetConvLayer( UpperCAmelCase__ , stride=UpperCAmelCase__ , groups=UpperCAmelCase__ , activation=config.hidden_act , name="layer.1" ), TFRegNetSELayer(UpperCAmelCase__ , reduced_channels=int(round(in_channels / 4 ) ) , name="layer.2" ), TFRegNetConvLayer(UpperCAmelCase__ , kernel_size=1 , activation=UpperCAmelCase__ , name="layer.3" ), ] __SCREAMING_SNAKE_CASE = ACTaFN[config.hidden_act] def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = hidden_state for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.shortcut(UpperCAmelCase__ ) hidden_state += residual __SCREAMING_SNAKE_CASE = self.activation(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : str , UpperCAmelCase__ : RegNetConfig , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int = 2 , UpperCAmelCase__ : int = 2 , **UpperCAmelCase__ : Optional[int] ) -> Optional[Any]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __SCREAMING_SNAKE_CASE = [ # downsampling is done in the first layer with stride of 2 layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , stride=UpperCAmelCase__ , name="layers.0" ), *[layer(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int ) -> int: for layer_module in self.layers: __SCREAMING_SNAKE_CASE = layer_module(UpperCAmelCase__ ) return hidden_state class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : RegNetConfig , **UpperCAmelCase__ : Any ) -> List[str]: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( UpperCAmelCase__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name="stages.0" , ) ) __SCREAMING_SNAKE_CASE = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(UpperCAmelCase__ , config.depths[1:] ) ): self.stages.append(TFRegNetStage(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , depth=UpperCAmelCase__ , name=F"""stages.{i+1}""" ) ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : bool = False , UpperCAmelCase__ : bool = True ) -> TFBaseModelOutputWithNoAttention: __SCREAMING_SNAKE_CASE = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) __SCREAMING_SNAKE_CASE = stage_module(UpperCAmelCase__ ) if output_hidden_states: __SCREAMING_SNAKE_CASE = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=UpperCAmelCase__ , hidden_states=UpperCAmelCase__ ) @keras_serializable class UpperCamelCase_ ( tf.keras.layers.Layer): """simple docstring""" snake_case__ : Any = RegNetConfig def __init__( self : List[Any] , UpperCAmelCase__ : Optional[Any] , **UpperCAmelCase__ : int ) -> Tuple: super().__init__(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config __SCREAMING_SNAKE_CASE = TFRegNetEmbeddings(UpperCAmelCase__ , name="embedder" ) __SCREAMING_SNAKE_CASE = TFRegNetEncoder(UpperCAmelCase__ , name="encoder" ) __SCREAMING_SNAKE_CASE = tf.keras.layers.GlobalAveragePoolingaD(keepdims=UpperCAmelCase__ , name="pooler" ) @unpack_inputs def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : bool = False , ) -> TFBaseModelOutputWithPoolingAndNoAttention: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.embedder(UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.encoder( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = encoder_outputs[0] __SCREAMING_SNAKE_CASE = self.pooler(UpperCAmelCase__ ) # Change to NCHW output format have uniformity in the modules __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) __SCREAMING_SNAKE_CASE = tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __SCREAMING_SNAKE_CASE = tuple([tf.transpose(UpperCAmelCase__ , perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCAmelCase__ , pooler_output=UpperCAmelCase__ , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = RegNetConfig snake_case__ : List[str] = "regnet" snake_case__ : str = "pixel_values" @property def UpperCAmelCase_ ( self : Optional[Any] ) -> Tuple: return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_2_4, 2_2_4) , dtype=tf.floataa )} a__ : Union[str, Any] = r''' Parameters: This model is a Tensorflow [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and behavior. config ([`RegNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights. ''' a__ : Optional[int] = r''' Args: pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConveNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : int , **UpperCAmelCase__ : Optional[int] ) -> Tuple: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : tf.Tensor , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Optional[bool] = None , UpperCAmelCase__ : Dict=False , ) -> Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( pixel_values=UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ , ) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , ) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , UpperCamelCase , ) class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : RegNetConfig , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Tuple ) -> Any: super().__init__(UpperCAmelCase__ , *UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = config.num_labels __SCREAMING_SNAKE_CASE = TFRegNetMainLayer(UpperCAmelCase__ , name="regnet" ) # classification head __SCREAMING_SNAKE_CASE = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels , name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(UpperCAmelCase__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCAmelCase__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : tf.Tensor = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : bool = None , UpperCAmelCase__ : Optional[Any]=False , ) -> Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]: __SCREAMING_SNAKE_CASE = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __SCREAMING_SNAKE_CASE = return_dict if return_dict is not None else self.config.use_return_dict __SCREAMING_SNAKE_CASE = self.regnet( UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__ , return_dict=UpperCAmelCase__ , training=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs.pooler_output if return_dict else outputs[1] __SCREAMING_SNAKE_CASE = self.classifier[0](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.classifier[1](UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = None if labels is None else self.hf_compute_loss(labels=UpperCAmelCase__ , logits=UpperCAmelCase__ ) if not return_dict: __SCREAMING_SNAKE_CASE = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=UpperCAmelCase__ , logits=UpperCAmelCase__ , hidden_states=outputs.hidden_states )
682
1
"""simple docstring""" import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''): a__ : List[str] = True from torch.cuda.amp import autocast a__ : int = logging.getLogger(__name__) def UpperCAmelCase__ (lowerCAmelCase_=None , lowerCAmelCase_=None ): '''simple docstring''' return field(default_factory=lambda: default , metadata=lowerCAmelCase_ ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) snake_case__ : Optional[bool] = field( default=UpperCamelCase , metadata={"help": "Whether to freeze the feature extractor layers of the model."}) snake_case__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout ratio for the attention probabilities."}) snake_case__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout ratio for activations inside the fully connected layer."}) snake_case__ : Optional[float] = field( default=0.1 , metadata={ "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler." } , ) snake_case__ : Optional[float] = field( default=0.1 , metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} , ) snake_case__ : Optional[float] = field( default=0.05 , metadata={ "help": ( "Propability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." ) } , ) snake_case__ : Optional[float] = field(default=0.0 , metadata={"help": "The LayerDrop probability."}) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}) snake_case__ : Optional[str] = field( default="train+validation" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Overwrite the cached preprocessed datasets or not."}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={"help": "The number of processes to use for the preprocessing."} , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) } , ) snake_case__ : List[str] = list_field( default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "'", "\"", "�"] , metadata={"help": "A list of characters to remove from the transcripts."} , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : WavaVecaProcessor snake_case__ : Union[bool, str] = True snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None snake_case__ : Optional[int] = None def __call__( self : List[str] , UpperCAmelCase__ : List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Dict[str, torch.Tensor]: # split inputs and labels since they have to be of different lenghts and need # different padding methods __SCREAMING_SNAKE_CASE = [{"input_values": feature["input_values"]} for feature in features] __SCREAMING_SNAKE_CASE = [{"input_ids": feature["labels"]} for feature in features] __SCREAMING_SNAKE_CASE = self.processor.pad( UpperCAmelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" , ) __SCREAMING_SNAKE_CASE = self.processor.pad( labels=UpperCAmelCase__ , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors="pt" , ) # replace padding with -100 to ignore loss correctly __SCREAMING_SNAKE_CASE = labels_batch["input_ids"].masked_fill(labels_batch.attention_mask.ne(1 ) , -1_0_0 ) __SCREAMING_SNAKE_CASE = labels return batch class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : nn.Module , UpperCAmelCase__ : Dict[str, Union[torch.Tensor, Any]] ) -> torch.Tensor: model.train() __SCREAMING_SNAKE_CASE = self._prepare_inputs(UpperCAmelCase__ ) if self.use_amp: with autocast(): __SCREAMING_SNAKE_CASE = self.compute_loss(UpperCAmelCase__ , UpperCAmelCase__ ) else: __SCREAMING_SNAKE_CASE = self.compute_loss(UpperCAmelCase__ , UpperCAmelCase__ ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": __SCREAMING_SNAKE_CASE = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": __SCREAMING_SNAKE_CASE = loss.sum() / (inputs["labels"] >= 0).sum() else: raise ValueError(F"""{model.config.ctc_loss_reduction} is not valid. Choose one of ['mean', 'sum']""" ) if self.args.gradient_accumulation_steps > 1: __SCREAMING_SNAKE_CASE = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(UpperCAmelCase__ ).backward() elif self.use_apex: with amp.scale_loss(UpperCAmelCase__ , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(UpperCAmelCase__ ) else: loss.backward() return loss.detach() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. """ "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}""" + f"""distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: __SCREAMING_SNAKE_CASE = datasets.load_dataset( "common_voice" , data_args.dataset_config_name , split=data_args.train_split_name ) __SCREAMING_SNAKE_CASE = datasets.load_dataset("common_voice" , data_args.dataset_config_name , split="test" ) # Create and save tokenizer __SCREAMING_SNAKE_CASE = f"""[{''.join(data_args.chars_to_ignore )}]""" def remove_special_characters(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.sub(lowerCAmelCase_ , "" , batch["sentence"] ).lower() + " " return batch __SCREAMING_SNAKE_CASE = train_dataset.map(lowerCAmelCase_ , remove_columns=["sentence"] ) __SCREAMING_SNAKE_CASE = eval_dataset.map(lowerCAmelCase_ , remove_columns=["sentence"] ) def extract_all_chars(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = " ".join(batch["text"] ) __SCREAMING_SNAKE_CASE = list(set(lowerCAmelCase_ ) ) return {"vocab": [vocab], "all_text": [all_text]} __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , batch_size=-1 , keep_in_memory=lowerCAmelCase_ , remove_columns=train_dataset.column_names , ) __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , batch_size=-1 , keep_in_memory=lowerCAmelCase_ , remove_columns=eval_dataset.column_names , ) __SCREAMING_SNAKE_CASE = list(set(vocab_train["vocab"][0] ) | set(vocab_test["vocab"][0] ) ) __SCREAMING_SNAKE_CASE = {v: k for k, v in enumerate(lowerCAmelCase_ )} __SCREAMING_SNAKE_CASE = vocab_dict[" "] del vocab_dict[" "] __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) with open("vocab.json" , "w" ) as vocab_file: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __SCREAMING_SNAKE_CASE = WavaVecaCTCTokenizer( "vocab.json" , unk_token="[UNK]" , pad_token="[PAD]" , word_delimiter_token="|" , ) __SCREAMING_SNAKE_CASE = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6000 , padding_value=0.0 , do_normalize=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = WavaVecaProcessor(feature_extractor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction="mean" , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = min(len(lowerCAmelCase_ ) , data_args.max_train_samples ) __SCREAMING_SNAKE_CASE = train_dataset.select(range(lowerCAmelCase_ ) ) if data_args.max_val_samples is not None: __SCREAMING_SNAKE_CASE = eval_dataset.select(range(data_args.max_val_samples ) ) __SCREAMING_SNAKE_CASE = torchaudio.transforms.Resample(4_8000 , 1_6000 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = torchaudio.load(batch["path"] ) __SCREAMING_SNAKE_CASE = resampler(lowerCAmelCase_ ).squeeze().numpy() __SCREAMING_SNAKE_CASE = 1_6000 __SCREAMING_SNAKE_CASE = batch["text"] return batch __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(lowerCAmelCase_ ): # check that all files have the correct sampling rate assert ( len(set(batch["sampling_rate"] ) ) == 1 ), f"""Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.""" __SCREAMING_SNAKE_CASE = processor( audio=batch["speech"] , text=batch["target_text"] , sampling_rate=batch["sampling_rate"][0] ) batch.update(lowerCAmelCase_ ) return batch __SCREAMING_SNAKE_CASE = train_dataset.map( lowerCAmelCase_ , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , ) __SCREAMING_SNAKE_CASE = eval_dataset.map( lowerCAmelCase_ , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=lowerCAmelCase_ , num_proc=data_args.preprocessing_num_workers , ) # Metric __SCREAMING_SNAKE_CASE = datasets.load_metric("wer" ) def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = pred.predictions __SCREAMING_SNAKE_CASE = np.argmax(lowerCAmelCase_ , axis=-1 ) __SCREAMING_SNAKE_CASE = processor.tokenizer.pad_token_id __SCREAMING_SNAKE_CASE = processor.batch_decode(lowerCAmelCase_ ) # we do not want to group tokens when computing the metrics __SCREAMING_SNAKE_CASE = processor.batch_decode(pred.label_ids , group_tokens=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = wer_metric.compute(predictions=lowerCAmelCase_ , references=lowerCAmelCase_ ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator __SCREAMING_SNAKE_CASE = DataCollatorCTCWithPadding(processor=lowerCAmelCase_ , padding=lowerCAmelCase_ ) # Initialize our Trainer __SCREAMING_SNAKE_CASE = CTCTrainer( model=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , args=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): __SCREAMING_SNAKE_CASE = model_args.model_name_or_path else: __SCREAMING_SNAKE_CASE = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() __SCREAMING_SNAKE_CASE = train_result.metrics __SCREAMING_SNAKE_CASE = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("train" , lowerCAmelCase_ ) trainer.save_metrics("train" , lowerCAmelCase_ ) trainer.save_state() # Evaluation __SCREAMING_SNAKE_CASE = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) __SCREAMING_SNAKE_CASE = trainer.evaluate() __SCREAMING_SNAKE_CASE = data_args.max_val_samples if data_args.max_val_samples is not None else len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = min(lowerCAmelCase_ , len(lowerCAmelCase_ ) ) trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) return results if __name__ == "__main__": main()
682
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return 3 * ((25 + 10 * (5 ** (1 / 2))) ** (1 / 2)) * (edge**2) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if edge <= 0 or not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise ValueError("Length must be a positive." ) return ((15 + (7 * (5 ** (1 / 2)))) / 4) * (edge**3) if __name__ == "__main__": import doctest doctest.testmod()
682
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[str] = logging.get_logger(__name__) a__ : str = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "realm" def __init__( self : Dict , UpperCAmelCase__ : Any=3_0_5_2_2 , UpperCAmelCase__ : List[Any]=7_6_8 , UpperCAmelCase__ : List[Any]=1_2_8 , UpperCAmelCase__ : Tuple=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Tuple=8 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_new" , UpperCAmelCase__ : List[str]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : List[Any]=5_1_2 , UpperCAmelCase__ : Optional[int]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : int=1E-12 , UpperCAmelCase__ : str=2_5_6 , UpperCAmelCase__ : List[str]=1_0 , UpperCAmelCase__ : str=1E-3 , UpperCAmelCase__ : Tuple=5 , UpperCAmelCase__ : int=3_2_0 , UpperCAmelCase__ : Union[str, Any]=1_3_3_5_3_7_1_8 , UpperCAmelCase__ : List[str]=5_0_0_0 , UpperCAmelCase__ : Tuple=1 , UpperCAmelCase__ : int=0 , UpperCAmelCase__ : Union[str, Any]=2 , **UpperCAmelCase__ : Optional[int] , ) -> List[Any]: super().__init__(pad_token_id=UpperCAmelCase__ , bos_token_id=UpperCAmelCase__ , eos_token_id=UpperCAmelCase__ , **UpperCAmelCase__ ) # Common config __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = retriever_proj_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = num_candidates __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = layer_norm_eps # Reader config __SCREAMING_SNAKE_CASE = span_hidden_size __SCREAMING_SNAKE_CASE = max_span_width __SCREAMING_SNAKE_CASE = reader_layer_norm_eps __SCREAMING_SNAKE_CASE = reader_beam_size __SCREAMING_SNAKE_CASE = reader_seq_len # Retrieval config __SCREAMING_SNAKE_CASE = num_block_records __SCREAMING_SNAKE_CASE = searcher_beam_size
682
"""simple docstring""" import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = r''' Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax or scores for each vocabulary token after SoftMax. kwargs (`Dict[str, Any]`, *optional*): Additional stopping criteria specific kwargs. Return: `bool`. `False` indicates we should continue, `True` indicates we should stop. ''' class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[Any] ) -> bool: raise NotImplementedError("StoppingCriteria needs to be subclassed" ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int] = None ) -> Optional[int]: __SCREAMING_SNAKE_CASE = max_length __SCREAMING_SNAKE_CASE = max_position_embeddings @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : List[str] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Optional[int] ) -> bool: __SCREAMING_SNAKE_CASE = input_ids.shape[-1] __SCREAMING_SNAKE_CASE = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( "This is a friendly reminder - the current text generation call will exceed the model's predefined " F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """ "exceptions, performance degradation, or nothing at all." ) return is_done class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> str: warnings.warn( "The class `MaxNewTokensCriteria` is deprecated. " F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """ "with `max_length = start_length + max_new_tokens` instead." , UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = start_length __SCREAMING_SNAKE_CASE = max_new_tokens __SCREAMING_SNAKE_CASE = start_length + max_new_tokens @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Union[str, Any] , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : Tuple ) -> bool: return input_ids.shape[-1] >= self.max_length class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : float , UpperCAmelCase__ : Optional[float] = None ) -> Dict: __SCREAMING_SNAKE_CASE = max_time __SCREAMING_SNAKE_CASE = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Tuple , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : str ) -> bool: return time.time() - self.initial_timestamp > self.max_time class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" @add_start_docstrings(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : torch.LongTensor , UpperCAmelCase__ : torch.FloatTensor , **UpperCAmelCase__ : List[str] ) -> bool: return any(criteria(UpperCAmelCase__ , UpperCAmelCase__ ) for criteria in self ) @property def UpperCAmelCase_ ( self : Any ) -> Optional[int]: for stopping_criterium in self: if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length elif isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): return stopping_criterium.max_length return None def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = stopping_criteria.max_length __SCREAMING_SNAKE_CASE = deepcopy(lowerCAmelCase_ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter" , lowerCAmelCase_ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowerCAmelCase_ ) ) return new_stopping_criteria
682
1
"""simple docstring""" import argparse import glob import logging import os import time from argparse import Namespace import numpy as np import torch from lightning_base import BaseTransformer, add_generic_args, generic_train from torch.utils.data import DataLoader, TensorDataset from transformers import glue_compute_metrics as compute_metrics from transformers import glue_convert_examples_to_features as convert_examples_to_features from transformers import glue_output_modes, glue_tasks_num_labels from transformers import glue_processors as processors a__ : int = logging.getLogger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "sequence-classification" def __init__( self : Dict , UpperCAmelCase__ : List[str] ) -> List[Any]: if type(UpperCAmelCase__ ) == dict: __SCREAMING_SNAKE_CASE = Namespace(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = glue_output_modes[hparams.task] __SCREAMING_SNAKE_CASE = glue_tasks_num_labels[hparams.task] super().__init__(UpperCAmelCase__ , UpperCAmelCase__ , self.mode ) def UpperCAmelCase_ ( self : Any , **UpperCAmelCase__ : Any ) -> Any: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[str]: __SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __SCREAMING_SNAKE_CASE = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __SCREAMING_SNAKE_CASE = self(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = outputs[0] __SCREAMING_SNAKE_CASE = self.trainer.lr_schedulers[0]["scheduler"] __SCREAMING_SNAKE_CASE = {"loss": loss, "rate": lr_scheduler.get_last_lr()[-1]} return {"loss": loss, "log": tensorboard_logs} def UpperCAmelCase_ ( self : Tuple ) -> Tuple: __SCREAMING_SNAKE_CASE = self.hparams __SCREAMING_SNAKE_CASE = processors[args.task]() __SCREAMING_SNAKE_CASE = processor.get_labels() for mode in ["train", "dev"]: __SCREAMING_SNAKE_CASE = self._feature_file(UpperCAmelCase__ ) if os.path.exists(UpperCAmelCase__ ) and not args.overwrite_cache: logger.info("Loading features from cached file %s" , UpperCAmelCase__ ) else: logger.info("Creating features from dataset file at %s" , args.data_dir ) __SCREAMING_SNAKE_CASE = ( processor.get_dev_examples(args.data_dir ) if mode == "dev" else processor.get_train_examples(args.data_dir ) ) __SCREAMING_SNAKE_CASE = convert_examples_to_features( UpperCAmelCase__ , self.tokenizer , max_length=args.max_seq_length , label_list=self.labels , output_mode=args.glue_output_mode , ) logger.info("Saving features into cached file %s" , UpperCAmelCase__ ) torch.save(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : bool = False ) -> DataLoader: __SCREAMING_SNAKE_CASE = "dev" if mode == "test" else mode __SCREAMING_SNAKE_CASE = self._feature_file(UpperCAmelCase__ ) logger.info("Loading features from cached file %s" , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.load(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([f.input_ids for f in features] , dtype=torch.long ) __SCREAMING_SNAKE_CASE = torch.tensor([f.attention_mask for f in features] , dtype=torch.long ) __SCREAMING_SNAKE_CASE = torch.tensor([f.token_type_ids for f in features] , dtype=torch.long ) if self.hparams.glue_output_mode == "classification": __SCREAMING_SNAKE_CASE = torch.tensor([f.label for f in features] , dtype=torch.long ) elif self.hparams.glue_output_mode == "regression": __SCREAMING_SNAKE_CASE = torch.tensor([f.label for f in features] , dtype=torch.float ) return DataLoader( TensorDataset(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) , batch_size=UpperCAmelCase__ , shuffle=UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = {"input_ids": batch[0], "attention_mask": batch[1], "labels": batch[3]} if self.config.model_type not in ["distilbert", "bart"]: __SCREAMING_SNAKE_CASE = batch[2] if self.config.model_type in ["bert", "xlnet", "albert"] else None __SCREAMING_SNAKE_CASE = self(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs[:2] __SCREAMING_SNAKE_CASE = logits.detach().cpu().numpy() __SCREAMING_SNAKE_CASE = inputs["labels"].detach().cpu().numpy() return {"val_loss": tmp_eval_loss.detach().cpu(), "pred": preds, "target": out_label_ids} def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] ) -> tuple: __SCREAMING_SNAKE_CASE = torch.stack([x["val_loss"] for x in outputs] ).mean().detach().cpu().item() __SCREAMING_SNAKE_CASE = np.concatenate([x["pred"] for x in outputs] , axis=0 ) if self.hparams.glue_output_mode == "classification": __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ , axis=1 ) elif self.hparams.glue_output_mode == "regression": __SCREAMING_SNAKE_CASE = np.squeeze(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.concatenate([x["target"] for x in outputs] , axis=0 ) __SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] __SCREAMING_SNAKE_CASE = [[] for _ in range(out_label_ids.shape[0] )] __SCREAMING_SNAKE_CASE = {**{"val_loss": val_loss_mean}, **compute_metrics(self.hparams.task , UpperCAmelCase__ , UpperCAmelCase__ )} __SCREAMING_SNAKE_CASE = dict(results.items() ) __SCREAMING_SNAKE_CASE = results return ret, preds_list, out_label_list def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : list ) -> dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._eval_end(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ret["log"] return {"val_loss": logs["val_loss"], "log": logs, "progress_bar": logs} def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple ) -> dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self._eval_end(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ret["log"] # `val_loss` is the key returned by `self._eval_end()` but actually refers to `test_loss` return {"avg_test_loss": logs["val_loss"], "log": logs, "progress_bar": logs} @staticmethod def UpperCAmelCase_ ( UpperCAmelCase__ : int , UpperCAmelCase__ : Dict ) -> List[str]: BaseTransformer.add_model_specific_args(UpperCAmelCase__ , UpperCAmelCase__ ) parser.add_argument( "--max_seq_length" , default=1_2_8 , type=UpperCAmelCase__ , help=( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) , ) parser.add_argument( "--task" , default="" , type=UpperCAmelCase__ , required=UpperCAmelCase__ , help="The GLUE task to run" , ) parser.add_argument( "--gpus" , default=0 , type=UpperCAmelCase__ , help="The number of GPUs allocated for this, it is by default 0 meaning none" , ) parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets" ) return parser def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() add_generic_args(lowerCAmelCase_ , os.getcwd() ) __SCREAMING_SNAKE_CASE = GLUETransformer.add_model_specific_args(lowerCAmelCase_ , os.getcwd() ) __SCREAMING_SNAKE_CASE = parser.parse_args() # If output_dir not provided, a folder will be generated in pwd if args.output_dir is None: __SCREAMING_SNAKE_CASE = os.path.join( "./results" , f"""{args.task}_{time.strftime('%Y%m%d_%H%M%S' )}""" , ) os.makedirs(args.output_dir ) __SCREAMING_SNAKE_CASE = GLUETransformer(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = generic_train(lowerCAmelCase_ , lowerCAmelCase_ ) # Optionally, predict on dev set and write to output_dir if args.do_predict: __SCREAMING_SNAKE_CASE = sorted(glob.glob(os.path.join(args.output_dir , "checkpoint-epoch=*.ckpt" ) , recursive=lowerCAmelCase_ ) ) __SCREAMING_SNAKE_CASE = model.load_from_checkpoint(checkpoints[-1] ) return trainer.test(lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _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 UpperCamelCase_ ( UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : int = RoCBertTokenizer snake_case__ : int = None snake_case__ : Optional[Any] = False snake_case__ : int = True snake_case__ : Any = filter_non_english def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: super().setUp() __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "你", "好", "是", "谁", "a", "b", "c", "d"] __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = {} for i, value in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_shape_file"] ) __SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["word_pronunciation_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) with open(self.word_shape_file , "w" , encoding="utf-8" ) as word_shape_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) with open(self.word_pronunciation_file , "w" , encoding="utf-8" ) as word_pronunciation_writer: json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> List[str]: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.tokenize("你好[SEP]你是谁" ) self.assertListEqual(UpperCAmelCase__ , ["你", "好", "[SEP]", "你", "是", "谁"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] ) def UpperCAmelCase_ ( self : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Any ) -> Optional[int]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCAmelCase_ ( self : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCAmelCase_ ( self : str ) -> List[str]: __SCREAMING_SNAKE_CASE = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __SCREAMING_SNAKE_CASE = {} for i, token in enumerate(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = i __SCREAMING_SNAKE_CASE = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , 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 UpperCAmelCase_ ( self : List[Any] ) -> str: 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 UpperCAmelCase_ ( self : List[Any] ) -> List[str]: 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 UpperCAmelCase_ ( self : List[str] ) -> Tuple: 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 UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) if self.test_rust_tokenizer: __SCREAMING_SNAKE_CASE = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ["Test", "\xad", "test"]] , [["[UNK]"], [], ["[UNK]"]] ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = F"""A, naïve {tokenizer_r.mask_token} AllenNLP sentence.""" __SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus( UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , "do_lower_case" ) else False __SCREAMING_SNAKE_CASE = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "Allen"), ((2_1, 2_3), "##NL"), ((2_3, 2_4), "##P"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), "allen"), ((2_1, 2_3), "##nl"), ((2_3, 2_4), "##p"), ((2_5, 3_3), "sentence"), ((3_3, 3_4), "."), ((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 UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = ["的", "人", "有"] __SCREAMING_SNAKE_CASE = "".join(UpperCAmelCase__ ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ ) # it is expected that only the first Chinese character is not preceded by "##". __SCREAMING_SNAKE_CASE = [ F"""##{token}""" if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ ) ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你好" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode("你是谁" , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def UpperCAmelCase_ ( self : str ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.get_tokenizers(do_lower_case=UpperCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): __SCREAMING_SNAKE_CASE = "你好,你是谁" __SCREAMING_SNAKE_CASE = tokenizer.tokenize(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.prepare_for_model( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer a__ : List[Any] = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Optional[Any] = { '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } a__ : str = { '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } a__ : Union[str, Any] = { '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Union[str, Any] = VOCAB_FILES_NAMES snake_case__ : Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ : List[str] = PRETRAINED_INIT_CONFIGURATION snake_case__ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Dict = ElectraTokenizer def __init__( self : List[Any] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : str="[UNK]" , UpperCAmelCase__ : Dict="[SEP]" , UpperCAmelCase__ : List[Any]="[PAD]" , UpperCAmelCase__ : int="[CLS]" , UpperCAmelCase__ : Any="[MASK]" , UpperCAmelCase__ : int=True , UpperCAmelCase__ : Optional[Any]=None , **UpperCAmelCase__ : Tuple , ) -> Optional[int]: super().__init__( UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , do_lower_case=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , sep_token=UpperCAmelCase__ , pad_token=UpperCAmelCase__ , cls_token=UpperCAmelCase__ , mask_token=UpperCAmelCase__ , tokenize_chinese_chars=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , UpperCAmelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , UpperCAmelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , UpperCAmelCase__ ) != tokenize_chinese_chars ): __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , normalizer_state.pop("type" ) ) __SCREAMING_SNAKE_CASE = do_lower_case __SCREAMING_SNAKE_CASE = strip_accents __SCREAMING_SNAKE_CASE = tokenize_chinese_chars __SCREAMING_SNAKE_CASE = normalizer_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = do_lower_case def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any=None ) -> Dict: __SCREAMING_SNAKE_CASE = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[int] , UpperCAmelCase__ : Optional[List[int]] = None ) -> List[int]: __SCREAMING_SNAKE_CASE = [self.sep_token_id] __SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ )
682
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Union[str, Any] = logging.get_logger(__name__) a__ : Optional[int] = { '''google/vivit-b-16x2-kinetics400''': ( '''https://huggingface.co/google/vivit-b-16x2-kinetics400/resolve/main/config.json''' ), # See all Vivit models at https://huggingface.co/models?filter=vivit } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[int] = "vivit" def __init__( self : Dict , UpperCAmelCase__ : Dict=2_2_4 , UpperCAmelCase__ : List[Any]=3_2 , UpperCAmelCase__ : str=[2, 1_6, 1_6] , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : str=7_6_8 , UpperCAmelCase__ : Dict=1_2 , UpperCAmelCase__ : Optional[int]=1_2 , UpperCAmelCase__ : Any=3_0_7_2 , UpperCAmelCase__ : Optional[int]="gelu_fast" , UpperCAmelCase__ : Tuple=0.0 , UpperCAmelCase__ : Union[str, Any]=0.0 , UpperCAmelCase__ : Optional[int]=0.02 , UpperCAmelCase__ : str=1E-06 , UpperCAmelCase__ : List[Any]=True , **UpperCAmelCase__ : Any , ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_frames __SCREAMING_SNAKE_CASE = tubelet_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = qkv_bias super().__init__(**UpperCAmelCase__ )
682
1
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] create_all_state(1 , lowerCAmelCase_ , lowerCAmelCase_ , [] , lowerCAmelCase_ ) return result def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ): '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(lowerCAmelCase_ , total_number - level + 2 ): current_list.append(lowerCAmelCase_ ) create_all_state(i + 1 , lowerCAmelCase_ , level - 1 , lowerCAmelCase_ , lowerCAmelCase_ ) current_list.pop() def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for i in total_list: print(*lowerCAmelCase_ ) if __name__ == "__main__": a__ : Tuple = 4 a__ : Dict = 2 a__ : int = generate_all_combinations(n, k) print_all_state(total_list)
682
"""simple docstring""" import numpy as np from transformers import Pipeline def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = np.max(lowerCAmelCase_ , axis=-1 , keepdims=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=lowerCAmelCase_ ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Tuple , **UpperCAmelCase__ : str ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if "second_text" in kwargs: __SCREAMING_SNAKE_CASE = kwargs["second_text"] return preprocess_kwargs, {}, {} def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=None ) -> str: return self.tokenizer(UpperCAmelCase__ , text_pair=UpperCAmelCase__ , return_tensors=self.framework ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: return self.model(**UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = model_outputs.logits[0].numpy() __SCREAMING_SNAKE_CASE = softmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = np.argmax(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.model.config.idalabel[best_class] __SCREAMING_SNAKE_CASE = probabilities[best_class].item() __SCREAMING_SNAKE_CASE = logits.tolist() return {"label": label, "score": score, "logits": logits}
682
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available a__ : Any = { '''configuration_conditional_detr''': [ '''CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConditionalDetrConfig''', '''ConditionalDetrOnnxConfig''', ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Tuple = ['''ConditionalDetrFeatureExtractor'''] a__ : List[Any] = ['''ConditionalDetrImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Dict = [ '''CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConditionalDetrForObjectDetection''', '''ConditionalDetrForSegmentation''', '''ConditionalDetrModel''', '''ConditionalDetrPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_CONFIG_ARCHIVE_MAP, ConditionalDetrConfig, ConditionalDetrOnnxConfig, ) try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_conditional_detr import ConditionalDetrFeatureExtractor from .image_processing_conditional_detr import ConditionalDetrImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_conditional_detr import ( CONDITIONAL_DETR_PRETRAINED_MODEL_ARCHIVE_LIST, ConditionalDetrForObjectDetection, ConditionalDetrForSegmentation, ConditionalDetrModel, ConditionalDetrPreTrainedModel, ) else: import sys a__ : Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
682
"""simple docstring""" import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) __SCREAMING_SNAKE_CASE = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) __SCREAMING_SNAKE_CASE = components[:-1] + [test_fn.replace(".py" , "" )] __SCREAMING_SNAKE_CASE = ".".join(lowerCAmelCase_ ) return test_module_path def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_module_path(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = importlib.import_module(lowerCAmelCase_ ) return test_module def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(lowerCAmelCase_ , lowerCAmelCase_ ) ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = get_test_module(lowerCAmelCase_ ) for attr in dir(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). __SCREAMING_SNAKE_CASE = getattr(lowerCAmelCase_ , "all_model_classes" , [] ) if len(lowerCAmelCase_ ) > 0: test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = test_class() if hasattr(lowerCAmelCase_ , "setUp" ): test.setUp() __SCREAMING_SNAKE_CASE = None if hasattr(lowerCAmelCase_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: __SCREAMING_SNAKE_CASE = test.model_tester.__class__ return model_tester def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = [] for test_class in test_classes: __SCREAMING_SNAKE_CASE = get_model_tester_from_test_class(lowerCAmelCase_ ) if tester_class is not None: tester_classes.append(lowerCAmelCase_ ) # sort with class names return sorted(lowerCAmelCase_ , key=lambda lowerCAmelCase_ : x.__name__ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_test_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = {test_class: get_model_tester_from_test_class(lowerCAmelCase_ ) for test_class in test_classes} return test_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_test_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_test_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = get_model_classes(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { model_class: get_tester_classes_for_model(lowerCAmelCase_ , lowerCAmelCase_ ) for model_class in model_classes } return model_to_tester_mapping def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return o.__name__ elif isinstance(lowerCAmelCase_ , (list, tuple) ): return [to_json(lowerCAmelCase_ ) for x in o] elif isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return {to_json(lowerCAmelCase_ ): to_json(lowerCAmelCase_ ) for k, v in o.items()} else: return o
682
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False")) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env") @parameterized_class( [ { "framework": "pytorch", "script": "run_glue_model_parallelism.py", "model_name_or_path": "roberta-large", "instance_type": "ml.p3dn.24xlarge", "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, }, { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "roberta-large", "instance_type": "ml.p3dn.24xlarge", "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, }, ]) class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : Any ) -> List[Any]: if self.framework == "pytorch": subprocess.run( F"""cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py""".split() , encoding="utf-8" , check=UpperCAmelCase__ , ) assert hasattr(self , "env" ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[str] ) -> List[Any]: # configuration for running training on smdistributed Model Parallel __SCREAMING_SNAKE_CASE = { "enabled": True, "processes_per_host": 8, } __SCREAMING_SNAKE_CASE = { "enabled": True, "parameters": { "microbatches": 4, "placement_strategy": "spread", "pipeline": "interleaved", "optimize": "speed", "partitions": 4, "ddp": True, }, } __SCREAMING_SNAKE_CASE = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options} __SCREAMING_SNAKE_CASE = "trainer" if self.script == "run_glue.py" else "smtrainer" # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"""{self.env.base_job_name}-{instance_count}-smp-{name_extension}""" , instance_count=UpperCAmelCase__ , instance_type=self.instance_type , debugger_hook_config=UpperCAmelCase__ , hyperparameters={ **self.env.hyperparameters, "model_name_or_path": self.model_name_or_path, "max_steps": 5_0_0, } , metric_definitions=self.env.metric_definitions , distribution=UpperCAmelCase__ , py_version="py36" , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : List[str] ) -> Tuple: TrainingJobAnalytics(UpperCAmelCase__ ).export_csv(F"""{self.env.test_path}/{job_name}_metrics.csv""" ) @parameterized.expand([(1,)] ) def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[Any] ) -> Union[str, Any]: # create estimator __SCREAMING_SNAKE_CASE = self.create_estimator(UpperCAmelCase__ ) # run training estimator.fit() # result dataframe __SCREAMING_SNAKE_CASE = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __SCREAMING_SNAKE_CASE = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) __SCREAMING_SNAKE_CASE = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __SCREAMING_SNAKE_CASE = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"""{estimator.latest_training_job.name}.json""" , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , UpperCAmelCase__ )
682
"""simple docstring""" # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_npu_available, is_xpu_available def UpperCAmelCase__ (lowerCAmelCase_=None ): '''simple docstring''' if subparsers is not None: __SCREAMING_SNAKE_CASE = subparsers.add_parser("env" ) else: __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("Accelerate env command" ) parser.add_argument( "--config_file" , default=lowerCAmelCase_ , help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=lowerCAmelCase_ ) return parser def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.__version__ __SCREAMING_SNAKE_CASE = torch.cuda.is_available() __SCREAMING_SNAKE_CASE = is_xpu_available() __SCREAMING_SNAKE_CASE = is_npu_available() __SCREAMING_SNAKE_CASE = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = load_config_from_file(args.config_file ).to_dict() __SCREAMING_SNAKE_CASE = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"""{pt_version} ({pt_cuda_available})""", "PyTorch XPU available": str(lowerCAmelCase_ ), "PyTorch NPU available": str(lowerCAmelCase_ ), "System RAM": f"""{psutil.virtual_memory().total / 1024 ** 3:.2f} GB""", } if pt_cuda_available: __SCREAMING_SNAKE_CASE = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n" ) print("\n".join([f"""- {prop}: {val}""" for prop, val in info.items()] ) ) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:" ) __SCREAMING_SNAKE_CASE = ( "\n".join([f"""\t- {prop}: {val}""" for prop, val in accelerate_config.items()] ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else f"""\t{accelerate_config}""" ) print(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = accelerate_config return info def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = env_command_parser() __SCREAMING_SNAKE_CASE = parser.parse_args() env_command(lowerCAmelCase_ ) return 0 if __name__ == "__main__": raise SystemExit(main())
682
1
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return 1 if input_a == input_a else 0 def UpperCAmelCase__ (): '''simple docstring''' assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
682
"""simple docstring""" import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets a__ : int = ''' @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415 }, @inproceedings{post-2018-call, title = "A Call for Clarity in Reporting {BLEU} Scores", author = "Post, Matt", booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers", month = oct, year = "2018", address = "Belgium, Brussels", publisher = "Association for Computational Linguistics", url = "https://www.aclweb.org/anthology/W18-6319", pages = "186--191", } ''' a__ : Union[str, Any] = '''\ WIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU It can be used to evaluate the quality of machine-generated texts. ''' a__ : Optional[Any] = ''' Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score sacrebleu: sacrebleu score exact: exact score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known ."]] >>> wiki_split = datasets.load_metric("wiki_split") >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0} ''' def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' def remove_articles(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = re.compile(R"\b(a|an|the)\b" , re.UNICODE ) return re.sub(lowerCAmelCase_ , " " , lowerCAmelCase_ ) def white_space_fix(lowerCAmelCase_ ): return " ".join(text.split() ) def remove_punc(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowerCAmelCase_ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowerCAmelCase_ ) ) ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return int(normalize_answer(lowerCAmelCase_ ) == normalize_answer(lowerCAmelCase_ ) ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [any(compute_exact(lowerCAmelCase_ , lowerCAmelCase_ ) for ref in refs ) for pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ )] return (sum(lowerCAmelCase_ ) / len(lowerCAmelCase_ )) * 100 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [rgram for rgrams in rgramslist for rgram in rgrams] __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for sgram, scount in sgramcounter.items(): __SCREAMING_SNAKE_CASE = scount * numref __SCREAMING_SNAKE_CASE = Counter(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = Counter() for cgram, ccount in cgramcounter.items(): __SCREAMING_SNAKE_CASE = ccount * numref # KEEP __SCREAMING_SNAKE_CASE = sgramcounter_rep & cgramcounter_rep __SCREAMING_SNAKE_CASE = keepgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep & rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = keeptmpscorea / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __SCREAMING_SNAKE_CASE = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __SCREAMING_SNAKE_CASE = 0 if keepscore_precision > 0 or keepscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __SCREAMING_SNAKE_CASE = sgramcounter_rep - cgramcounter_rep __SCREAMING_SNAKE_CASE = delgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = sgramcounter_rep - rgramcounter __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = deltmpscorea / len(lowerCAmelCase_ ) # ADDITION __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) & set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = set(lowerCAmelCase_ ) - set(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 1 if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: __SCREAMING_SNAKE_CASE = addtmpscore / len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = 0 if addscore_precision > 0 or addscore_recall > 0: __SCREAMING_SNAKE_CASE = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ssent.split(" " ) __SCREAMING_SNAKE_CASE = csent.split(" " ) __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 = [] __SCREAMING_SNAKE_CASE = [] for rsent in rsents: __SCREAMING_SNAKE_CASE = rsent.split(" " ) __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = [] ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] ragrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = ragrams[i] + " " + ragrams[i + 1] + " " + ragrams[i + 2] + " " + ragrams[i + 3] ragrams.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) ragramslist.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] sagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = sagrams[i] + " " + sagrams[i + 1] + " " + sagrams[i + 2] + " " + sagrams[i + 3] sagrams.append(lowerCAmelCase_ ) for i in range(0 , len(lowerCAmelCase_ ) - 1 ): if i < len(lowerCAmelCase_ ) - 1: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 2: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] cagrams.append(lowerCAmelCase_ ) if i < len(lowerCAmelCase_ ) - 3: __SCREAMING_SNAKE_CASE = cagrams[i] + " " + cagrams[i + 1] + " " + cagrams[i + 2] + " " + cagrams[i + 3] cagrams.append(lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ((__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE) , (__SCREAMING_SNAKE_CASE)) = SARIngram(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([delascore, delascore, delascore, delascore] ) / 4 __SCREAMING_SNAKE_CASE = sum([addascore, addascore, addascore, addascore] ) / 4 __SCREAMING_SNAKE_CASE = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = True , lowerCAmelCase_ = "13a" , lowerCAmelCase_ = True ): '''simple docstring''' if lowercase: __SCREAMING_SNAKE_CASE = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __SCREAMING_SNAKE_CASE = sacrebleu.metrics.bleu._get_tokenizer(lowerCAmelCase_ )()(lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sacrebleu.TOKENIZERS[tokenizer]()(lowerCAmelCase_ ) elif tokenizer == "moses": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ , escape=lowerCAmelCase_ ) elif tokenizer == "penn": __SCREAMING_SNAKE_CASE = sacremoses.MosesTokenizer().penn_tokenize(lowerCAmelCase_ , return_str=lowerCAmelCase_ ) else: __SCREAMING_SNAKE_CASE = sentence if not return_str: __SCREAMING_SNAKE_CASE = normalized_sent.split() return normalized_sent def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if not (len(lowerCAmelCase_ ) == len(lowerCAmelCase_ ) == len(lowerCAmelCase_ )): raise ValueError("Sources length must match predictions and references lengths." ) __SCREAMING_SNAKE_CASE = 0 for src, pred, refs in zip(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): sari_score += SARIsent(normalize(lowerCAmelCase_ ) , normalize(lowerCAmelCase_ ) , [normalize(lowerCAmelCase_ ) for sent in refs] ) __SCREAMING_SNAKE_CASE = sari_score / len(lowerCAmelCase_ ) return 100 * sari_score def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_="exp" , lowerCAmelCase_=None , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=False , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = len(references[0] ) if any(len(lowerCAmelCase_ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) __SCREAMING_SNAKE_CASE = [[refs[i] for refs in references] for i in range(lowerCAmelCase_ )] __SCREAMING_SNAKE_CASE = sacrebleu.corpus_bleu( lowerCAmelCase_ , lowerCAmelCase_ , smooth_method=lowerCAmelCase_ , smooth_value=lowerCAmelCase_ , force=lowerCAmelCase_ , lowercase=lowerCAmelCase_ , use_effective_order=lowerCAmelCase_ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCamelCase_ ( datasets.Metric): """simple docstring""" def UpperCAmelCase_ ( self : Dict ) -> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=[ "https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py", "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", "https://github.com/mjpost/sacreBLEU", ] , reference_urls=[ "https://www.aclweb.org/anthology/Q16-1029.pdf", "https://github.com/mjpost/sacreBLEU", "https://en.wikipedia.org/wiki/BLEU", "https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213", ] , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} result.update({"sari": compute_sari(sources=UpperCAmelCase__ , predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"sacrebleu": compute_sacrebleu(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) result.update({"exact": compute_em(predictions=UpperCAmelCase__ , references=UpperCAmelCase__ )} ) return result
682
1
"""simple docstring""" 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 # and perform 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 # ######################################################################## a__ : Union[str, Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : Tuple = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # New Code # __SCREAMING_SNAKE_CASE = int(args.gradient_accumulation_steps ) # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=lowerCAmelCase_ ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) set_seed(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # 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(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = output.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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=lowerCAmelCase_ , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Union[str, Any]=1_3 , UpperCAmelCase__ : int=7 , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[int]=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Tuple=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : int=5 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=3_7 , UpperCAmelCase__ : int="gelu" , UpperCAmelCase__ : List[Any]=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Tuple=1_2_8 , UpperCAmelCase__ : Union[str, Any]=3_2 , UpperCAmelCase__ : Any=1_6 , UpperCAmelCase__ : Union[str, Any]=2 , UpperCAmelCase__ : Tuple=0.02 , UpperCAmelCase__ : str=3 , UpperCAmelCase__ : Tuple=4 , UpperCAmelCase__ : List[str]=None , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) 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 : List[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , ) -> Tuple: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = NezhaModel(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , encoder_attention_mask=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , encoder_hidden_states=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) 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 : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> int: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any ) -> Tuple: __SCREAMING_SNAKE_CASE = NezhaForNextSentencePrediction(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaForPreTraining(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , next_sentence_label=UpperCAmelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = NezhaForQuestionAnswering(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , start_positions=UpperCAmelCase__ , end_positions=UpperCAmelCase__ , ) 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 : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Any ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = NezhaForTokenClassification(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Any , UpperCAmelCase__ : Dict ) -> str: __SCREAMING_SNAKE_CASE = self.num_choices __SCREAMING_SNAKE_CASE = NezhaForMultipleChoice(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __SCREAMING_SNAKE_CASE = model( UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : str = ( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) snake_case__ : Tuple = ( { "feature-extraction": NezhaModel, "fill-mask": NezhaForMaskedLM, "question-answering": NezhaForQuestionAnswering, "text-classification": NezhaForSequenceClassification, "token-classification": NezhaForTokenClassification, "zero-shot": NezhaForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : int = True def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : int , UpperCAmelCase__ : Union[str, Any]=False ) -> Dict: __SCREAMING_SNAKE_CASE = super()._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ ) if return_labels: if model_class in get_values(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCAmelCase__ ) return inputs_dict def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = NezhaModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : int ) -> List[Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> List[Any]: # This regression test was failing with PyTorch < 1.3 ( ( __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 ) , ) = self.model_tester.prepare_config_and_inputs_for_decoder() __SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , ) def UpperCAmelCase_ ( self : Optional[int] ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : List[Any] ) -> int: for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) @slow @require_torch_gpu def UpperCAmelCase_ ( self : List[str] ) -> Optional[int]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = model_class(config=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.jit.trace( UpperCAmelCase__ , (inputs_dict["input_ids"].to("cpu" ), inputs_dict["attention_mask"].to("cpu" )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(UpperCAmelCase__ , os.path.join(UpperCAmelCase__ , "bert.pt" ) ) __SCREAMING_SNAKE_CASE = torch.jit.load(os.path.join(UpperCAmelCase__ , "bert.pt" ) , map_location=UpperCAmelCase__ ) loaded(inputs_dict["input_ids"].to(UpperCAmelCase__ ) , inputs_dict["attention_mask"].to(UpperCAmelCase__ ) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 7_6_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor([[[0.0_685, 0.2_441, 0.1_102], [0.0_600, 0.1_906, 0.1_349], [0.0_221, 0.0_819, 0.0_586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Optional[Any] ) -> Any: __SCREAMING_SNAKE_CASE = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) __SCREAMING_SNAKE_CASE = torch.tensor([[0, 1, 2, 3, 4, 5]] ) __SCREAMING_SNAKE_CASE = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = torch.Size((1, 6, 2_1_1_2_8) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[-2.7_939, -1.7_902, -2.2_189], [-2.8_585, -1.8_908, -2.3_723], [-2.6_499, -1.7_750, -2.2_558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCAmelCase__ , atol=1E-4 ) )
682
1
"""simple docstring""" # Function to print upper half of diamond (pyramid) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for i in range(0 , lowerCAmelCase_ ): for _ in range(0 , n - i - 1 ): # printing spaces print(" " , end="" ) for _ in range(0 , i + 1 ): # printing stars print("* " , end="" ) print() def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' for i in range(lowerCAmelCase_ , 0 , -1 ): for _ in range(lowerCAmelCase_ , 0 , -1 ): # printing stars print("* " , end="" ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(" " , end="" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if n <= 0: print(" ... .... nothing printing :(" ) return floyd(lowerCAmelCase_ ) # upper half reverse_floyd(lowerCAmelCase_ ) # lower half if __name__ == "__main__": print(r'''| /\ | |- | |- |--| |\ /| |-''') print(r'''|/ \| |- |_ |_ |__| | \/ | |_''') a__ : Tuple = 1 while K: a__ : Tuple = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) a__ : Any = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
682
"""simple docstring""" import os def UpperCAmelCase__ (): '''simple docstring''' with open(os.path.dirname(lowerCAmelCase_ ) + "/p022_names.txt" ) as file: __SCREAMING_SNAKE_CASE = str(file.readlines()[0] ) __SCREAMING_SNAKE_CASE = names.replace("\"" , "" ).split("," ) names.sort() __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 for i, name in enumerate(lowerCAmelCase_ ): for letter in name: name_score += ord(lowerCAmelCase_ ) - 64 total_score += (i + 1) * name_score __SCREAMING_SNAKE_CASE = 0 return total_score if __name__ == "__main__": print(solution())
682
1
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Union[str, Any] = '''▁''' a__ : str = {'''vocab_file''': '''spiece.model'''} a__ : Dict = { '''vocab_file''': { '''google/reformer-crime-and-punishment''': ( '''https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model''' ) } } a__ : Tuple = { '''google/reformer-crime-and-punishment''': 5_2_4_2_8_8, } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[str] = VOCAB_FILES_NAMES snake_case__ : int = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : int = ["input_ids", "attention_mask"] def __init__( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str]="</s>" , UpperCAmelCase__ : Union[str, Any]="<unk>" , UpperCAmelCase__ : Dict=[] , UpperCAmelCase__ : Optional[Dict[str, Any]] = None , **UpperCAmelCase__ : Union[str, Any] , ) -> None: __SCREAMING_SNAKE_CASE = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , additional_special_tokens=UpperCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = vocab_file __SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : int ) -> str: return self.sp_model.get_piece_size() def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict[str, int]: __SCREAMING_SNAKE_CASE = {self.convert_ids_to_tokens(UpperCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.__dict__.copy() __SCREAMING_SNAKE_CASE = None return state def __setstate__( self : Dict , UpperCAmelCase__ : str ) -> Dict: __SCREAMING_SNAKE_CASE = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __SCREAMING_SNAKE_CASE = {} __SCREAMING_SNAKE_CASE = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str ) -> List[str]: return self.sp_model.encode(UpperCAmelCase__ , out_type=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : List[str] ) -> int: return self.sp_model.piece_to_id(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : List[str] ) -> Tuple: if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE = self.sp_model.IdToPiece(UpperCAmelCase__ ) return token def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Any ) -> List[Any]: __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(UpperCAmelCase__ ) + token __SCREAMING_SNAKE_CASE = [] else: current_sub_tokens.append(UpperCAmelCase__ ) out_string += self.sp_model.decode(UpperCAmelCase__ ) return out_string.strip() def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(UpperCAmelCase__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return __SCREAMING_SNAKE_CASE = os.path.join( UpperCAmelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , UpperCAmelCase__ ) elif not os.path.isfile(self.vocab_file ): with open(UpperCAmelCase__ , "wb" ) as fi: __SCREAMING_SNAKE_CASE = self.sp_model.serialized_model_proto() fi.write(UpperCAmelCase__ ) return (out_vocab_file,)
682
"""simple docstring""" import argparse import os from io import BytesIO from pathlib import Path import requests from clip_retrieval.clip_client import ClipClient from PIL import Image from tqdm import tqdm def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = 1.5 __SCREAMING_SNAKE_CASE = int(factor * num_class_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 ) os.makedirs(f"""{class_data_dir}/images""" , exist_ok=lowerCAmelCase_ ) if len(list(Path(f"""{class_data_dir}/images""" ).iterdir() ) ) >= num_class_images: return while True: __SCREAMING_SNAKE_CASE = client.query(text=lowerCAmelCase_ ) if len(lowerCAmelCase_ ) >= factor * num_class_images or num_images > 1E4: break else: __SCREAMING_SNAKE_CASE = int(factor * num_images ) __SCREAMING_SNAKE_CASE = ClipClient( url="https://knn.laion.ai/knn-service" , indice_name="laion_400m" , num_images=lowerCAmelCase_ , aesthetic_weight=0.1 , ) __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = tqdm(desc="downloading real regularization images" , total=lowerCAmelCase_ ) with open(f"""{class_data_dir}/caption.txt""" , "w" ) as fa, open(f"""{class_data_dir}/urls.txt""" , "w" ) as fa, open( f"""{class_data_dir}/images.txt""" , "w" ) as fa: while total < num_class_images: __SCREAMING_SNAKE_CASE = class_images[count] count += 1 try: __SCREAMING_SNAKE_CASE = requests.get(images["url"] ) if img.status_code == 200: __SCREAMING_SNAKE_CASE = Image.open(BytesIO(img.content ) ) with open(f"""{class_data_dir}/images/{total}.jpg""" , "wb" ) as f: f.write(img.content ) fa.write(images["caption"] + "\n" ) fa.write(images["url"] + "\n" ) fa.write(f"""{class_data_dir}/images/{total}.jpg""" + "\n" ) total += 1 pbar.update(1 ) else: continue except Exception: continue return def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser("" , add_help=lowerCAmelCase_ ) parser.add_argument("--class_prompt" , help="text prompt to retrieve images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--class_data_dir" , help="path to save images" , required=lowerCAmelCase_ , type=lowerCAmelCase_ ) parser.add_argument("--num_class_images" , help="number of images to download" , default=200 , type=lowerCAmelCase_ ) return parser.parse_args() if __name__ == "__main__": a__ : Optional[Any] = parse_args() retrieve(args.class_prompt, args.class_data_dir, args.num_class_images)
682
1
"""simple docstring""" import logging import os import sys import warnings from dataclasses import dataclass, field from random import randint from typing import Optional import datasets import evaluate import numpy as np from datasets import DatasetDict, load_dataset import transformers from transformers import ( AutoConfig, AutoFeatureExtractor, AutoModelForAudioClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version a__ : int = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''') def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 1_6000 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = int(round(sample_rate * max_length ) ) if len(lowerCAmelCase_ ) <= sample_length: return wav __SCREAMING_SNAKE_CASE = randint(0 , len(lowerCAmelCase_ ) - sample_length - 1 ) return wav[random_offset : random_offset + sample_length] @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : Optional[str] = field(default=UpperCamelCase , metadata={"help": "Name of a dataset from the datasets package"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "A file containing the training audio paths and labels."}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "A file containing the validation audio paths and labels."}) snake_case__ : str = field( default="train" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'" } , ) snake_case__ : str = field( default="validation" , metadata={ "help": ( "The name of the training data set split to use (via the datasets library). Defaults to 'validation'" ) } , ) snake_case__ : str = field( default="audio" , metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"} , ) snake_case__ : str = field( default="label" , metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) snake_case__ : Optional[int] = field( default=UpperCamelCase , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) snake_case__ : float = field( default=20 , metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."} , ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str = field( default="facebook/wav2vec2-base" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Pretrained config name or path if not the same as model_name"}) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Where do you want to store the pretrained models downloaded from the Hub"}) snake_case__ : str = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) snake_case__ : Optional[str] = field( default=UpperCamelCase , metadata={"help": "Name or path of preprocessor config."}) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to freeze the feature encoder layers of the model."}) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Whether to generate an attention mask in the feature extractor."}) snake_case__ : bool = field( default=UpperCamelCase , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) snake_case__ : Optional[bool] = field( default=UpperCamelCase , metadata={"help": "Whether to freeze the feature extractor layers of the model."}) snake_case__ : bool = field( default=UpperCamelCase , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: if not self.freeze_feature_extractor and self.freeze_feature_encoder: warnings.warn( "The argument `--freeze_feature_extractor` is deprecated and " "will be removed in a future version. Use `--freeze_feature_encoder`" "instead. Setting `freeze_feature_encoder==True`." , UpperCAmelCase__ , ) if self.freeze_feature_extractor and not self.freeze_feature_encoder: raise ValueError( "The argument `--freeze_feature_extractor` is deprecated and " "should not be used in combination with `--freeze_feature_encoder`." "Only make use of `--freeze_feature_encoder`." ) def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = 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_audio_classification" , lowerCAmelCase_ , lowerCAmelCase_ ) # 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() __SCREAMING_SNAKE_CASE = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase_ ) transformers.utils.logging.set_verbosity(lowerCAmelCase_ ) 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}""" ) # Set seed before initializing model. set_seed(training_args.seed ) # Detecting last checkpoint. __SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __SCREAMING_SNAKE_CASE = 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 train from scratch." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( f"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """ "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset and prepare it for the audio classification task. __SCREAMING_SNAKE_CASE = DatasetDict() __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.train_split_name , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=data_args.eval_split_name , use_auth_token=True if model_args.use_auth_token else None , ) if data_args.audio_column_name not in raw_datasets["train"].column_names: raise ValueError( f"""--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. """ "Make sure to set `--audio_column_name` to the correct audio column - one of " f"""{', '.join(raw_datasets['train'].column_names )}.""" ) if data_args.label_column_name not in raw_datasets["train"].column_names: raise ValueError( f"""--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. """ "Make sure to set `--label_column_name` to the correct text column - one of " f"""{', '.join(raw_datasets['train'].column_names )}.""" ) # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over # transformer outputs in the classifier, but it doesn't always lead to better accuracy __SCREAMING_SNAKE_CASE = AutoFeatureExtractor.from_pretrained( model_args.feature_extractor_name or model_args.model_name_or_path , return_attention_mask=model_args.attention_mask , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # `datasets` takes care of automatically loading and resampling the audio, # so we just need to set the correct target sampling rate. __SCREAMING_SNAKE_CASE = raw_datasets.cast_column( data_args.audio_column_name , datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate ) ) __SCREAMING_SNAKE_CASE = feature_extractor.model_input_names[0] def train_transforms(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [] for audio in batch[data_args.audio_column_name]: __SCREAMING_SNAKE_CASE = random_subsample( audio["array"] , max_length=data_args.max_length_seconds , sample_rate=feature_extractor.sampling_rate ) subsampled_wavs.append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = feature_extractor(lowerCAmelCase_ , sampling_rate=feature_extractor.sampling_rate ) __SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(lowerCAmelCase_ )} __SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch def val_transforms(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = [audio["array"] for audio in batch[data_args.audio_column_name]] __SCREAMING_SNAKE_CASE = feature_extractor(lowerCAmelCase_ , sampling_rate=feature_extractor.sampling_rate ) __SCREAMING_SNAKE_CASE = {model_input_name: inputs.get(lowerCAmelCase_ )} __SCREAMING_SNAKE_CASE = list(batch[data_args.label_column_name] ) return output_batch # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. __SCREAMING_SNAKE_CASE = raw_datasets["train"].features[data_args.label_column_name].names __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = {}, {} for i, label in enumerate(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = str(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = label # Load the accuracy metric from the datasets package __SCREAMING_SNAKE_CASE = evaluate.load("accuracy" ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with # `predictions` and `label_ids` fields) and has to return a dictionary string to float. def compute_metrics(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = np.argmax(eval_pred.predictions , axis=1 ) return metric.compute(predictions=lowerCAmelCase_ , references=eval_pred.label_ids ) __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(lowerCAmelCase_ ) , labelaid=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , finetuning_task="audio-classification" , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __SCREAMING_SNAKE_CASE = AutoModelForAudioClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # freeze the convolutional waveform encoder if model_args.freeze_feature_encoder: model.freeze_feature_encoder() if training_args.do_train: if data_args.max_train_samples is not None: __SCREAMING_SNAKE_CASE = ( raw_datasets["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms raw_datasets["train"].set_transform(lowerCAmelCase_ , output_all_columns=lowerCAmelCase_ ) if training_args.do_eval: if data_args.max_eval_samples is not None: __SCREAMING_SNAKE_CASE = ( raw_datasets["eval"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms raw_datasets["eval"].set_transform(lowerCAmelCase_ , output_all_columns=lowerCAmelCase_ ) # Initialize our trainer __SCREAMING_SNAKE_CASE = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=raw_datasets["train"] if training_args.do_train else None , eval_dataset=raw_datasets["eval"] if training_args.do_eval else None , compute_metrics=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ , ) # Training if training_args.do_train: __SCREAMING_SNAKE_CASE = None if training_args.resume_from_checkpoint is not None: __SCREAMING_SNAKE_CASE = training_args.resume_from_checkpoint elif last_checkpoint is not None: __SCREAMING_SNAKE_CASE = last_checkpoint __SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=lowerCAmelCase_ ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: __SCREAMING_SNAKE_CASE = trainer.evaluate() trainer.log_metrics("eval" , lowerCAmelCase_ ) trainer.save_metrics("eval" , lowerCAmelCase_ ) # Write model card and (optionally) push to hub __SCREAMING_SNAKE_CASE = { "finetuned_from": model_args.model_name_or_path, "tasks": "audio-classification", "dataset": data_args.dataset_name, "tags": ["audio-classification"], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase_ ) else: trainer.create_model_card(**lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import enum import warnings from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a__ : str = logging.get_logger(__name__) class UpperCamelCase_ ( enum.Enum): """simple docstring""" snake_case__ : Optional[int] = 0 snake_case__ : Dict = 1 @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Tuple = "generated" def __init__( self : Any , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ) -> Dict: super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__ ) self.check_model_type( TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : Dict=None , **UpperCAmelCase__ : Union[str, Any] , ) -> Optional[int]: __SCREAMING_SNAKE_CASE = {} if truncation is not None: __SCREAMING_SNAKE_CASE = truncation __SCREAMING_SNAKE_CASE = generate_kwargs __SCREAMING_SNAKE_CASE = {} if return_tensors is not None and return_type is None: __SCREAMING_SNAKE_CASE = ReturnType.TENSORS if return_tensors else ReturnType.TEXT if return_type is not None: __SCREAMING_SNAKE_CASE = return_type if clean_up_tokenization_spaces is not None: __SCREAMING_SNAKE_CASE = clean_up_tokenization_spaces if stop_sequence is not None: __SCREAMING_SNAKE_CASE = self.tokenizer.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) if len(UpperCAmelCase__ ) > 1: warnings.warn( "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" " the stop sequence will be used as the stop sequence string in the interim." ) __SCREAMING_SNAKE_CASE = stop_sequence_ids[0] return preprocess_params, forward_params, postprocess_params def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> List[str]: return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : Dict , UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE = self.model.config.prefix if self.model.config.prefix is not None else "" if isinstance(args[0] , UpperCAmelCase__ ): if self.tokenizer.pad_token_id is None: raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input" ) __SCREAMING_SNAKE_CASE = ([prefix + arg for arg in args[0]],) __SCREAMING_SNAKE_CASE = True elif isinstance(args[0] , UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = (prefix + args[0],) __SCREAMING_SNAKE_CASE = False else: raise ValueError( F""" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`""" ) __SCREAMING_SNAKE_CASE = self.tokenizer(*UpperCAmelCase__ , padding=UpperCAmelCase__ , truncation=UpperCAmelCase__ , return_tensors=self.framework ) # This is produced by tokenizers but is an invalid generate kwargs if "token_type_ids" in inputs: del inputs["token_type_ids"] return inputs def __call__( self : List[str] , *UpperCAmelCase__ : Any , **UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) if ( isinstance(args[0] , UpperCAmelCase__ ) and all(isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) for el in args[0] ) and all(len(UpperCAmelCase__ ) == 1 for res in result ) ): return [res[0] for res in result] return result def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , **UpperCAmelCase__ : int ) -> Tuple: __SCREAMING_SNAKE_CASE = self._parse_and_tokenize(UpperCAmelCase__ , truncation=UpperCAmelCase__ , **UpperCAmelCase__ ) return inputs def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int , **UpperCAmelCase__ : Any ) -> Any: if self.framework == "pt": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model_inputs["input_ids"].shape elif self.framework == "tf": __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = tf.shape(model_inputs["input_ids"] ).numpy() __SCREAMING_SNAKE_CASE = generate_kwargs.get("min_length" , self.model.config.min_length ) __SCREAMING_SNAKE_CASE = generate_kwargs.get("max_length" , self.model.config.max_length ) self.check_inputs(UpperCAmelCase__ , generate_kwargs["min_length"] , generate_kwargs["max_length"] ) __SCREAMING_SNAKE_CASE = self.model.generate(**UpperCAmelCase__ , **UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = output_ids.shape[0] if self.framework == "pt": __SCREAMING_SNAKE_CASE = output_ids.reshape(UpperCAmelCase__ , out_b // in_b , *output_ids.shape[1:] ) elif self.framework == "tf": __SCREAMING_SNAKE_CASE = tf.reshape(UpperCAmelCase__ , (in_b, out_b // in_b, *output_ids.shape[1:]) ) return {"output_ids": output_ids} def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Dict=ReturnType.TEXT , UpperCAmelCase__ : str=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = [] for output_ids in model_outputs["output_ids"][0]: if return_type == ReturnType.TENSORS: __SCREAMING_SNAKE_CASE = {F"""{self.return_name}_token_ids""": output_ids} elif return_type == ReturnType.TEXT: __SCREAMING_SNAKE_CASE = { F"""{self.return_name}_text""": self.tokenizer.decode( UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ , clean_up_tokenization_spaces=UpperCAmelCase__ , ) } records.append(UpperCAmelCase__ ) return records @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "summary" def __call__( self : Tuple , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> Optional[int]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> bool: if max_length < min_length: logger.warning(F"""Your min_length={min_length} must be inferior than your max_length={max_length}.""" ) if input_length < max_length: logger.warning( F"""Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is """ "a summarization task, where outputs shorter than the input are typically wanted, you might " F"""consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length//2})""" ) @add_end_docstrings(UpperCamelCase) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : str = "translation" def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Optional[Any]: if input_length > 0.9 * max_length: logger.warning( F"""Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider """ "increasing your max_length manually, e.g. translator('...', max_length=400)" ) return True def UpperCAmelCase_ ( self : Any , *UpperCAmelCase__ : int , UpperCAmelCase__ : Optional[int]=TruncationStrategy.DO_NOT_TRUNCATE , UpperCAmelCase__ : Any=None , UpperCAmelCase__ : Optional[Any]=None ) -> List[Any]: if getattr(self.tokenizer , "_build_translation_inputs" , UpperCAmelCase__ ): return self.tokenizer._build_translation_inputs( *UpperCAmelCase__ , return_tensors=self.framework , truncation=UpperCAmelCase__ , src_lang=UpperCAmelCase__ , tgt_lang=UpperCAmelCase__ ) else: return super()._parse_and_tokenize(*UpperCAmelCase__ , truncation=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : str=None , **UpperCAmelCase__ : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = super()._sanitize_parameters(**UpperCAmelCase__ ) if src_lang is not None: __SCREAMING_SNAKE_CASE = src_lang if tgt_lang is not None: __SCREAMING_SNAKE_CASE = tgt_lang if src_lang is None and tgt_lang is None: # Backward compatibility, direct arguments use is preferred. __SCREAMING_SNAKE_CASE = kwargs.get("task" , self.task ) __SCREAMING_SNAKE_CASE = task.split("_" ) if task and len(UpperCAmelCase__ ) == 4: # translation, XX, to YY __SCREAMING_SNAKE_CASE = items[1] __SCREAMING_SNAKE_CASE = items[3] return preprocess_params, forward_params, postprocess_params def __call__( self : str , *UpperCAmelCase__ : Union[str, Any] , **UpperCAmelCase__ : Any ) -> List[Any]: return super().__call__(*UpperCAmelCase__ , **UpperCAmelCase__ )
682
1
"""simple docstring""" a__ : str = tuple[float, float, float] a__ : Dict = tuple[float, float, float] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = end_pointa[0] - end_pointa[0] __SCREAMING_SNAKE_CASE = end_pointa[1] - end_pointa[1] __SCREAMING_SNAKE_CASE = end_pointa[2] - end_pointa[2] return (x, y, z) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = ab[1] * ac[2] - ab[2] * ac[1] # *i __SCREAMING_SNAKE_CASE = (ab[0] * ac[2] - ab[2] * ac[0]) * -1 # *j __SCREAMING_SNAKE_CASE = ab[0] * ac[1] - ab[1] * ac[0] # *k return (x, y, z) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' return tuple(round(lowerCAmelCase_ , lowerCAmelCase_ ) for x in vector ) == (0, 0, 0) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = 10 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = create_vector(lowerCAmelCase_ , lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = create_vector(lowerCAmelCase_ , lowerCAmelCase_ ) return is_zero_vector(get_ad_vectors_cross(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ )
682
"""simple docstring""" import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : List[Any] = AutoencoderKL snake_case__ : Optional[Any] = "sample" snake_case__ : Optional[Any] = 1E-2 @property def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = (3_2, 3_2) __SCREAMING_SNAKE_CASE = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase__ ) return {"sample": image} @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: return (3, 3_2, 3_2) @property def UpperCAmelCase_ ( self : Dict ) -> Union[str, Any]: return (3, 3_2, 3_2) def UpperCAmelCase_ ( self : List[str] ) -> List[str]: __SCREAMING_SNAKE_CASE = { "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, } __SCREAMING_SNAKE_CASE = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase_ ( self : Optional[Any] ) -> List[str]: pass def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def UpperCAmelCase_ ( self : str ) -> List[Any]: # enable deterministic behavior for gradient checkpointing __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.prepare_init_args_and_inputs_for_common() __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) assert not model.is_gradient_checkpointing and model.training __SCREAMING_SNAKE_CASE = model(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model.zero_grad() __SCREAMING_SNAKE_CASE = torch.randn_like(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __SCREAMING_SNAKE_CASE = self.model_class(**UpperCAmelCase__ ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(UpperCAmelCase__ ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __SCREAMING_SNAKE_CASE = model_a(**UpperCAmelCase__ ).sample # run the backwards pass on the model. For backwards pass, for simplicity purpose, # we won't calculate the loss and rather backprop on out.sum() model_a.zero_grad() __SCREAMING_SNAKE_CASE = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __SCREAMING_SNAKE_CASE = dict(model.named_parameters() ) __SCREAMING_SNAKE_CASE = dict(model_a.named_parameters() ) for name, param in named_params.items(): self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5E-5 ) ) def UpperCAmelCase_ ( self : List[str] ) -> Any: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase_ ( self : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __SCREAMING_SNAKE_CASE = model.to(UpperCAmelCase__ ) model.eval() if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) else: __SCREAMING_SNAKE_CASE = torch.Generator(device=UpperCAmelCase__ ).manual_seed(0 ) __SCREAMING_SNAKE_CASE = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __SCREAMING_SNAKE_CASE = image.to(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ , generator=UpperCAmelCase__ ).sample __SCREAMING_SNAKE_CASE = output[0, -1, -3:, -3:].flatten().cpu() # Since the VAE Gaussian prior's generator is seeded on the appropriate device, # the expected output slices are not the same for CPU and GPU. if torch_device == "mps": __SCREAMING_SNAKE_CASE = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": __SCREAMING_SNAKE_CASE = torch.tensor( [-0.1_352, 0.0_878, 0.0_419, -0.0_818, -0.1_069, 0.0_688, -0.1_458, -0.4_446, -0.0_026] ) else: __SCREAMING_SNAKE_CASE = torch.tensor( [-0.2_421, 0.4_642, 0.2_507, -0.0_438, 0.0_682, 0.3_160, -0.2_018, -0.0_727, 0.2_485] ) self.assertTrue(torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , rtol=1E-2 ) ) @slow class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : List[str] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict ) -> Any: return F"""gaussian_noise_s={seed}_shape={'_'.join([str(UpperCAmelCase__ ) for s in shape] )}.npy""" def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Tuple=0 , UpperCAmelCase__ : Optional[Any]=(4, 3, 5_1_2, 5_1_2) , UpperCAmelCase__ : Any=False ) -> List[str]: __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase__ , UpperCAmelCase__ ) ) ).to(UpperCAmelCase__ ).to(UpperCAmelCase__ ) return image def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict="CompVis/stable-diffusion-v1-4" , UpperCAmelCase__ : Optional[Any]=False ) -> Tuple: __SCREAMING_SNAKE_CASE = "fp16" if fpaa else None __SCREAMING_SNAKE_CASE = torch.floataa if fpaa else torch.floataa __SCREAMING_SNAKE_CASE = AutoencoderKL.from_pretrained( UpperCAmelCase__ , subfolder="vae" , torch_dtype=UpperCAmelCase__ , revision=UpperCAmelCase__ , ) model.to(UpperCAmelCase__ ).eval() return model def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : int=0 ) -> str: if torch_device == "mps": return torch.manual_seed(UpperCAmelCase__ ) return torch.Generator(device=UpperCAmelCase__ ).manual_seed(UpperCAmelCase__ ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_603, 0.9_878, -0.0_495, -0.0_790, -0.2_709, 0.8_375, -0.2_060, -0.0_824], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_376, 0.1_168, 0.1_332, -0.4_840, -0.2_508, -0.0_791, -0.0_493, -0.4_089], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [3_3, [-0.0_513, 0.0_289, 1.3_799, 0.2_166, -0.2_573, -0.0_871, 0.5_103, -0.0_999]], [4_7, [-0.4_128, -0.1_320, -0.3_704, 0.1_965, -0.4_116, -0.2_332, -0.3_340, 0.2_247]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , generator=UpperCAmelCase__ , sample_posterior=UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.1_609, 0.9_866, -0.0_487, -0.0_777, -0.2_716, 0.8_368, -0.2_055, -0.0_814], [-0.2_395, 0.0_098, 0.0_102, -0.0_709, -0.2_840, -0.0_274, -0.0_718, -0.1_824]], [4_7, [-0.2_377, 0.1_147, 0.1_333, -0.4_841, -0.2_506, -0.0_805, -0.0_491, -0.4_085], [0.0_350, 0.0_847, 0.0_467, 0.0_344, -0.0_842, -0.0_547, -0.0_633, -0.1_131]], # fmt: on ] ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ).sample assert sample.shape == image.shape __SCREAMING_SNAKE_CASE = sample[-1, -2:, -2:, :2].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=3E-3 ) @parameterized.expand( [ # fmt: off [1_3, [-0.2_051, -0.1_803, -0.2_311, -0.2_114, -0.3_292, -0.3_574, -0.2_953, -0.3_323]], [3_7, [-0.2_632, -0.2_625, -0.2_199, -0.2_741, -0.4_539, -0.4_990, -0.3_720, -0.4_925]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ) -> str: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) @parameterized.expand( [ # fmt: off [2_7, [-0.0_369, 0.0_207, -0.0_776, -0.0_682, -0.1_747, -0.1_930, -0.1_465, -0.2_039]], [1_6, [-0.1_628, -0.2_134, -0.2_747, -0.2_642, -0.3_774, -0.4_404, -0.3_687, -0.4_277]], # fmt: on ] ) @require_torch_gpu def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] __SCREAMING_SNAKE_CASE = sample[-1, -2:, :2, -2:].flatten().float().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=5E-3 ) @parameterized.expand([(1_3,), (1_6,), (2_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model(fpaa=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) , fpaa=UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-1 ) @parameterized.expand([(1_3,), (1_6,), (3_7,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Tuple ) -> Dict: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ , shape=(3, 4, 6_4, 6_4) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.decode(UpperCAmelCase__ ).sample assert list(sample.shape ) == [3, 3, 5_1_2, 5_1_2] assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-2 ) @parameterized.expand( [ # fmt: off [3_3, [-0.3_001, 0.0_918, -2.6_984, -3.9_720, -3.2_099, -5.0_353, 1.7_338, -0.2_065, 3.4_267]], [4_7, [-1.5_030, -4.3_871, -6.0_355, -9.1_157, -1.6_661, -2.7_853, 2.1_607, -5.0_823, 2.5_633]], # fmt: on ] ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : str , UpperCAmelCase__ : Tuple ) -> Optional[int]: __SCREAMING_SNAKE_CASE = self.get_sd_vae_model() __SCREAMING_SNAKE_CASE = self.get_sd_image(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.get_generator(UpperCAmelCase__ ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model.encode(UpperCAmelCase__ ).latent_dist __SCREAMING_SNAKE_CASE = dist.sample(generator=UpperCAmelCase__ ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __SCREAMING_SNAKE_CASE = sample[0, -1, -3:, -3:].flatten().cpu() __SCREAMING_SNAKE_CASE = torch.tensor(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(UpperCAmelCase__ , UpperCAmelCase__ , atol=UpperCAmelCase__ )
682
1
"""simple docstring""" import importlib import json import os import sys import tempfile import unittest from pathlib import Path import transformers import transformers.models.auto from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.bert.configuration_bert import BertConfig from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 a__ : str = get_tests_dir('''fixtures/dummy-config.json''') class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" def UpperCAmelCase_ ( self : str ) -> Any: __SCREAMING_SNAKE_CASE = 0 def UpperCAmelCase_ ( self : str ) -> List[Any]: self.assertIsNotNone(transformers.models.auto.__spec__ ) self.assertIsNotNone(importlib.util.find_spec("transformers.models.auto" ) ) def UpperCAmelCase_ ( self : List[str] ) -> Tuple: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("bert-base-uncased" ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Any: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] ) -> Dict: __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> int: __SCREAMING_SNAKE_CASE = AutoConfig.for_model("roberta" ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: with tempfile.TemporaryDirectory() as tmp_dir: # This model name contains bert and roberta, but roberta ends up being picked. __SCREAMING_SNAKE_CASE = os.path.join(UpperCAmelCase__ , "fake-roberta" ) os.makedirs(UpperCAmelCase__ , exist_ok=UpperCAmelCase__ ) with open(os.path.join(UpperCAmelCase__ , "config.json" ) , "w" ) as f: f.write(json.dumps({} ) ) __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertEqual(type(UpperCAmelCase__ ) , UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> Optional[Any]: try: AutoConfig.register("custom" , UpperCAmelCase__ ) # Wrong model type will raise an error with self.assertRaises(UpperCAmelCase__ ): AutoConfig.register("model" , UpperCAmelCase__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCAmelCase__ ): AutoConfig.register("bert" , UpperCAmelCase__ ) # Now that the config is registered, it can be used as any other config with the auto-API __SCREAMING_SNAKE_CASE = CustomConfig() with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ ) self.assertIsInstance(UpperCAmelCase__ , UpperCAmelCase__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] def UpperCAmelCase_ ( self : List[Any] ) -> List[Any]: with self.assertRaisesRegex( UpperCAmelCase__ , "bert-base is not a local folder and is not a valid model identifier" ): __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("bert-base" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> str: with self.assertRaisesRegex( UpperCAmelCase__ , R"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ , revision="aaaaaa" ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Dict: with self.assertRaisesRegex( UpperCAmelCase__ , "hf-internal-testing/no-config-test-repo does not appear to have a file named config.json." , ): __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/no-config-test-repo" ) def UpperCAmelCase_ ( self : Union[str, Any] ) -> Optional[Any]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) # If remote code is disabled, we can't load this config. with self.assertRaises(UpperCAmelCase__ ): __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) # Test config can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(UpperCAmelCase__ , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(reloaded_config.__class__.__name__ , "NewModelConfig" ) def UpperCAmelCase_ ( self : Dict ) -> int: class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : int = "new-model" try: AutoConfig.register("new-model" , UpperCAmelCase__ ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfigLocal" ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained("hf-internal-testing/test_dynamic_model" , trust_remote_code=UpperCAmelCase__ ) self.assertEqual(config.__class__.__name__ , "NewModelConfig" ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"]
682
"""simple docstring""" import math import unittest from transformers import BioGptConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCamelCase_ : """simple docstring""" def __init__( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int=1_3 , UpperCAmelCase__ : Optional[Any]=7 , UpperCAmelCase__ : str=True , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=False , UpperCAmelCase__ : str=True , UpperCAmelCase__ : Optional[int]=9_9 , UpperCAmelCase__ : Dict=3_2 , UpperCAmelCase__ : List[str]=5 , UpperCAmelCase__ : Optional[int]=4 , UpperCAmelCase__ : Union[str, Any]=3_7 , UpperCAmelCase__ : Tuple="gelu" , UpperCAmelCase__ : Union[str, Any]=0.1 , UpperCAmelCase__ : Dict=0.1 , UpperCAmelCase__ : int=5_1_2 , UpperCAmelCase__ : List[str]=1_6 , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : List[Any]=0.02 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : str=4 , UpperCAmelCase__ : List[Any]=None , ) -> Any: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = seq_length __SCREAMING_SNAKE_CASE = is_training __SCREAMING_SNAKE_CASE = use_input_mask __SCREAMING_SNAKE_CASE = use_token_type_ids __SCREAMING_SNAKE_CASE = use_labels __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = type_sequence_label_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = num_choices __SCREAMING_SNAKE_CASE = scope def UpperCAmelCase_ ( self : int ) -> Dict: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __SCREAMING_SNAKE_CASE = None if self.use_input_mask: __SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) __SCREAMING_SNAKE_CASE = None if self.use_token_type_ids: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None if self.use_labels: __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_choices ) __SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase_ ( self : int ) -> Union[str, Any]: return BioGptConfig( 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=UpperCAmelCase__ , initializer_range=self.initializer_range , ) def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : int , UpperCAmelCase__ : int ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase_ ( self : int , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Optional[Any] ) -> Tuple: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() # create attention mask __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = self.seq_length // 2 __SCREAMING_SNAKE_CASE = 0 # first forward pass __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ ).to_tuple() # create hypothetical next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __SCREAMING_SNAKE_CASE = ids_tensor((1,) , UpperCAmelCase__ ).item() + 1 __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __SCREAMING_SNAKE_CASE = random_other_next_tokens # append to next input_ids and attn_mask __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=UpperCAmelCase__ )] , dim=1 , ) # get two different outputs __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , past_key_values=UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -1, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Union[str, Any] , *UpperCAmelCase__ : Optional[Any] ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptModel(config=UpperCAmelCase__ ).to(UpperCAmelCase__ ).eval() __SCREAMING_SNAKE_CASE = torch.ones(input_ids.shape , dtype=torch.long , device=UpperCAmelCase__ ) # first forward pass __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , use_cache=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , config.vocab_size ) __SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) __SCREAMING_SNAKE_CASE = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ )["last_hidden_state"] __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , past_key_values=UpperCAmelCase__ )[ "last_hidden_state" ] # select random slice __SCREAMING_SNAKE_CASE = ids_tensor((1,) , output_from_past.shape[-1] ).item() __SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() __SCREAMING_SNAKE_CASE = 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(UpperCAmelCase__ , UpperCAmelCase__ , atol=1E-3 ) ) def UpperCAmelCase_ ( self : str , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any , *UpperCAmelCase__ : Any , UpperCAmelCase__ : int=False ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase_ ( self : List[Any] , UpperCAmelCase__ : str , *UpperCAmelCase__ : Optional[int] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = BioGptModel(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : Optional[Any] , *UpperCAmelCase__ : Dict ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = self.num_labels __SCREAMING_SNAKE_CASE = BioGptForTokenClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , token_type_ids=UpperCAmelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase_ ( self : Optional[Any] ) -> str: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() ( ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ( __SCREAMING_SNAKE_CASE ) , ) = config_and_inputs __SCREAMING_SNAKE_CASE = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class UpperCamelCase_ ( UpperCamelCase , UpperCamelCase , UpperCamelCase , unittest.TestCase): """simple docstring""" snake_case__ : Union[str, Any] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) snake_case__ : Optional[int] = (BioGptForCausalLM,) if is_torch_available() else () snake_case__ : Tuple = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) snake_case__ : Optional[Any] = False def UpperCAmelCase_ ( self : Union[str, Any] ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=UpperCAmelCase__ , hidden_size=3_7 ) def UpperCAmelCase_ ( self : Tuple ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase_ ( self : List[str] ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : int ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __SCREAMING_SNAKE_CASE = type self.model_tester.create_and_check_model(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : List[Any] ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*UpperCAmelCase__ , gradient_checkpointing=UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Tuple ) -> List[Any]: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*UpperCAmelCase__ ) @slow def UpperCAmelCase_ ( self : int ) -> List[str]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = "left" # Define PAD Token = EOS Token = 50256 __SCREAMING_SNAKE_CASE = tokenizer.eos_token __SCREAMING_SNAKE_CASE = model.config.eos_token_id # use different length sentences to test batching __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little", "Today, I", ] __SCREAMING_SNAKE_CASE = tokenizer(UpperCAmelCase__ , return_tensors="pt" , padding=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs["input_ids"].to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( input_ids=UpperCAmelCase__ , attention_mask=inputs["attention_mask"].to(UpperCAmelCase__ ) , ) __SCREAMING_SNAKE_CASE = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __SCREAMING_SNAKE_CASE = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate(input_ids=UpperCAmelCase__ , max_length=model.config.max_length - num_paddings ) __SCREAMING_SNAKE_CASE = tokenizer.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_non_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_padded[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ ) self.assertListEqual(UpperCAmelCase__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE = BioGptModel.from_pretrained(UpperCAmelCase__ ) self.assertIsNotNone(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Dict ) -> Dict: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase_ ( self : List[Any] ) -> str: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = 3 __SCREAMING_SNAKE_CASE = "multi_label_classification" __SCREAMING_SNAKE_CASE = input_dict["input_ids"] __SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __SCREAMING_SNAKE_CASE = BioGptForSequenceClassification(UpperCAmelCase__ ) model.to(UpperCAmelCase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ , attention_mask=UpperCAmelCase__ , labels=UpperCAmelCase__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class UpperCamelCase_ ( unittest.TestCase): """simple docstring""" @slow def UpperCAmelCase_ ( self : int ) -> List[Any]: __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = torch.tensor([[2, 4_8_0_5, 9, 6_5_6, 2_1]] ) __SCREAMING_SNAKE_CASE = model(UpperCAmelCase__ )[0] __SCREAMING_SNAKE_CASE = 4_2_3_8_4 __SCREAMING_SNAKE_CASE = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = torch.tensor( [[[-9.5_236, -9.8_918, 10.4_557], [-11.0_469, -9.6_423, 8.1_022], [-8.8_664, -7.8_826, 5.5_325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCAmelCase__ , atol=1E-4 ) ) @slow def UpperCAmelCase_ ( self : Union[str, Any] ) -> int: __SCREAMING_SNAKE_CASE = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __SCREAMING_SNAKE_CASE = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(UpperCAmelCase__ ) torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE = tokenizer("COVID-19 is" , return_tensors="pt" ).to(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = model.generate( **UpperCAmelCase__ , min_length=1_0_0 , max_length=1_0_2_4 , num_beams=5 , early_stopping=UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = tokenizer.decode(output_ids[0] , skip_special_tokens=UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
682
1
"""simple docstring""" import argparse import os # New Code # import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils import find_executable_batch_size ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing how to ensure out-of-memory errors never # interrupt training, and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a__ : Optional[Any] = 1_6 a__ : str = 3_2 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 16 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("bert-base-cased" ) __SCREAMING_SNAKE_CASE = load_dataset("glue" , "mrpc" ) def tokenize_function(lowerCAmelCase_ ): # max_length=None => use the model max length (it's actually the default) __SCREAMING_SNAKE_CASE = 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 # starting with the main process first: with accelerator.main_process_first(): __SCREAMING_SNAKE_CASE = datasets.map( lowerCAmelCase_ , batched=lowerCAmelCase_ , 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 __SCREAMING_SNAKE_CASE = 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. __SCREAMING_SNAKE_CASE = 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": __SCREAMING_SNAKE_CASE = 16 elif accelerator.mixed_precision != "no": __SCREAMING_SNAKE_CASE = 8 else: __SCREAMING_SNAKE_CASE = None return tokenizer.pad( lowerCAmelCase_ , padding="longest" , max_length=lowerCAmelCase_ , pad_to_multiple_of=lowerCAmelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["train"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = DataLoader( tokenized_datasets["validation"] , shuffle=lowerCAmelCase_ , collate_fn=lowerCAmelCase_ , batch_size=lowerCAmelCase_ ) 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 a__ : List[Any] = mocked_dataloaders # noqa: F811 def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , lowerCAmelCase_ ) == "1": __SCREAMING_SNAKE_CASE = 2 # Initialize accelerator __SCREAMING_SNAKE_CASE = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __SCREAMING_SNAKE_CASE = config["lr"] __SCREAMING_SNAKE_CASE = int(config["num_epochs"] ) __SCREAMING_SNAKE_CASE = int(config["seed"] ) __SCREAMING_SNAKE_CASE = int(config["batch_size"] ) __SCREAMING_SNAKE_CASE = evaluate.load("glue" , "mrpc" ) # New Code # # We now can define an inner training loop function. It should take a batch size as the only parameter, # and build the dataloaders in there. # It also gets our decorator @find_executable_batch_size(starting_batch_size=lowerCAmelCase_ ) def inner_training_loop(lowerCAmelCase_ ): # And now just move everything below under this function # We need to bring in the Accelerator object from earlier nonlocal accelerator # And reset all of its attributes that could hold onto any memory: accelerator.free_memory() # Then we can declare the model, optimizer, and everything else: set_seed(lowerCAmelCase_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=lowerCAmelCase_ ) # 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). __SCREAMING_SNAKE_CASE = model.to(accelerator.device ) # Instantiate optimizer __SCREAMING_SNAKE_CASE = AdamW(params=model.parameters() , lr=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = get_dataloaders(lowerCAmelCase_ , lowerCAmelCase_ ) # Instantiate scheduler __SCREAMING_SNAKE_CASE = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase_ , num_warmup_steps=100 , num_training_steps=(len(lowerCAmelCase_ ) * 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. __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.prepare( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # Now we train the model for epoch in range(lowerCAmelCase_ ): model.train() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.loss accelerator.backward(lowerCAmelCase_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(lowerCAmelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(**lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=lowerCAmelCase_ , references=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , lowerCAmelCase_ ) # New Code # # And call it at the end with no arguments # Note: You could also refactor this outside of your training loop function inner_training_loop() def UpperCAmelCase__ (): '''simple docstring''' __SCREAMING_SNAKE_CASE = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=lowerCAmelCase_ , default=lowerCAmelCase_ , 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." ) __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
682
"""simple docstring""" import os import pytest from attr import dataclass a__ : int = '''us-east-1''' # defaults region @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : str snake_case__ : Optional[Any] = "arn:aws:iam::558105141721:role/sagemaker_execution_role" snake_case__ : Optional[Any] = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } snake_case__ : Tuple = {**hyperparameters, "max_steps": 1000} @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self : int ) -> str: return F"""{self.framework}-transfromers-test""" @property def UpperCAmelCase_ ( self : List[Any] ) -> str: return F"""./tests/sagemaker/scripts/{self.framework}""" @property def UpperCAmelCase_ ( self : Any ) -> str: if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope="class" ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = SageMakerTestEnvironment(framework=request.cls.framework )
682
1
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() a__ : Optional[int] = logging.get_logger() @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : nn.Module snake_case__ : List[nn.Module] = field(default_factory=UpperCamelCase) snake_case__ : list = field(default_factory=UpperCamelCase) def UpperCAmelCase_ ( self : Union[str, Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : Tensor , UpperCAmelCase__ : Tensor ) -> Any: __SCREAMING_SNAKE_CASE = len(list(m.modules() ) ) == 1 or isinstance(UpperCAmelCase__ , nn.Convad ) or isinstance(UpperCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(UpperCAmelCase__ ) def __call__( self : Dict , UpperCAmelCase__ : Tensor ) -> int: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(UpperCAmelCase__ ) [x.remove() for x in self.handles] return self @property def UpperCAmelCase_ ( self : Optional[int] ) -> Tuple: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda UpperCAmelCase__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class UpperCamelCase_ : """simple docstring""" snake_case__ : nn.Module snake_case__ : nn.Module snake_case__ : int = 1 snake_case__ : List = field(default_factory=UpperCamelCase) snake_case__ : List = field(default_factory=UpperCamelCase) snake_case__ : bool = True def __call__( self : int , UpperCAmelCase__ : Tensor ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = Tracker(self.dest )(UpperCAmelCase__ ).parametrized __SCREAMING_SNAKE_CASE = Tracker(self.src )(UpperCAmelCase__ ).parametrized __SCREAMING_SNAKE_CASE = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.src_skip , UpperCAmelCase__ ) ) __SCREAMING_SNAKE_CASE = list(filter(lambda UpperCAmelCase__ : type(UpperCAmelCase__ ) not in self.dest_skip , UpperCAmelCase__ ) ) if len(UpperCAmelCase__ ) != len(UpperCAmelCase__ ) and self.raise_if_mismatch: raise Exception( F"""Numbers of operations are different. Source module has {len(UpperCAmelCase__ )} operations while""" F""" destination module has {len(UpperCAmelCase__ )}.""" ) for dest_m, src_m in zip(UpperCAmelCase__ , UpperCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F"""Transfered from={src_m} to={dest_m}""" ) class UpperCamelCase_ ( nn.Module): """simple docstring""" def __init__( self : Optional[int] , UpperCAmelCase__ : nn.Module ) -> List[Any]: super().__init__() __SCREAMING_SNAKE_CASE = [] # - get the stem feature_blocks.append(("conv1", model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith("block" ), F"""Unexpected layer name {k}""" __SCREAMING_SNAKE_CASE = len(UpperCAmelCase__ ) + 1 feature_blocks.append((F"""res{block_index}""", v) ) __SCREAMING_SNAKE_CASE = nn.ModuleDict(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Any , UpperCAmelCase__ : Tensor ) -> Optional[Any]: return get_trunk_forward_outputs( UpperCAmelCase__ , out_feat_keys=UpperCAmelCase__ , feature_blocks=self._feature_blocks , ) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def UpperCAmelCase_ ( self : Optional[Any] , UpperCAmelCase__ : str ) -> str: __SCREAMING_SNAKE_CASE = x.split("-" ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Optional[int] , UpperCAmelCase__ : str ) -> Callable[[], Tuple[nn.Module, Dict]]: # default to timm! if x not in self: __SCREAMING_SNAKE_CASE = self.convert_name_to_timm(UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = partial(lambda: (timm.create_model(UpperCAmelCase__ , pretrained=UpperCAmelCase__ ).eval(), None) ) else: __SCREAMING_SNAKE_CASE = super().__getitem__(UpperCAmelCase__ ) return val class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __getitem__( self : List[str] , UpperCAmelCase__ : str ) -> Callable[[], nn.Module]: if "seer" in x and "in1k" not in x: __SCREAMING_SNAKE_CASE = RegNetModel else: __SCREAMING_SNAKE_CASE = RegNetForImageClassification return val def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' for from_key, to_key in keys: __SCREAMING_SNAKE_CASE = from_state_dict[from_key].clone() print(f"""Copied key={from_key} to={to_key}""" ) return to_state_dict def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = True , ): '''simple docstring''' print(f"""Converting {name}...""" ) with torch.no_grad(): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = from_model_func() __SCREAMING_SNAKE_CASE = our_model_func(lowerCAmelCase_ ).eval() __SCREAMING_SNAKE_CASE = ModuleTransfer(src=lowerCAmelCase_ , dest=lowerCAmelCase_ , raise_if_mismatch=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = torch.randn((1, 3, 224, 224) ) module_transfer(lowerCAmelCase_ ) if from_state_dict is not None: __SCREAMING_SNAKE_CASE = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: __SCREAMING_SNAKE_CASE = [("0.clf.0.weight", "classifier.1.weight"), ("0.clf.0.bias", "classifier.1.bias")] __SCREAMING_SNAKE_CASE = manually_copy_vissl_head(lowerCAmelCase_ , our_model.state_dict() , lowerCAmelCase_ ) our_model.load_state_dict(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = our_model(lowerCAmelCase_ , output_hidden_states=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = ( our_outputs.logits if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else our_outputs.last_hidden_state ) __SCREAMING_SNAKE_CASE = from_model(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = from_output[-1] if type(lowerCAmelCase_ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: __SCREAMING_SNAKE_CASE = our_outputs.hidden_states[-1] assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add model" , use_temp_dir=lowerCAmelCase_ , ) __SCREAMING_SNAKE_CASE = 224 if "seer" not in name else 384 # we can use the convnext one __SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" , size=lowerCAmelCase_ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message="Add image processor" , use_temp_dir=lowerCAmelCase_ , ) print(f"""Pushed {name}""" ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = True ): '''simple docstring''' __SCREAMING_SNAKE_CASE = "imagenet-1k-id2label.json" __SCREAMING_SNAKE_CASE = 1000 __SCREAMING_SNAKE_CASE = (1, num_labels) __SCREAMING_SNAKE_CASE = "huggingface/label-files" __SCREAMING_SNAKE_CASE = num_labels __SCREAMING_SNAKE_CASE = json.load(open(cached_download(hf_hub_url(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) ) , "r" ) ) __SCREAMING_SNAKE_CASE = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = idalabel __SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} __SCREAMING_SNAKE_CASE = partial(lowerCAmelCase_ , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid=lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = { "regnet-x-002": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type="x" ), "regnet-x-004": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type="x" ), "regnet-x-006": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type="x" ), "regnet-x-008": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type="x" ), "regnet-x-016": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type="x" ), "regnet-x-032": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type="x" ), "regnet-x-040": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type="x" ), "regnet-x-064": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type="x" ), "regnet-x-080": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type="x" ), "regnet-x-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type="x" ), "regnet-x-160": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type="x" ), "regnet-x-320": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type="x" ), # y variant "regnet-y-002": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), "regnet-y-004": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), "regnet-y-006": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), "regnet-y-008": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), "regnet-y-016": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), "regnet-y-032": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), "regnet-y-040": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), "regnet-y-064": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), "regnet-y-080": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), "regnet-y-120": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), "regnet-y-160": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), "regnet-y-320": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 "regnet-y-320-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), # finetuned on imagenet "regnet-y-320-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), "regnet-y-640-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), "regnet-y-1280-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), "regnet-y-2560-seer-in1k": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), "regnet-y-10b-seer-in1k": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), } __SCREAMING_SNAKE_CASE = NameToOurModelFuncMap() __SCREAMING_SNAKE_CASE = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple[nn.Module, Dict]: __SCREAMING_SNAKE_CASE = torch.hub.load_state_dict_from_url(lowerCAmelCase_ , model_dir=str(lowerCAmelCase_ ) , map_location="cpu" ) __SCREAMING_SNAKE_CASE = model_func() # check if we have a head, if yes add it __SCREAMING_SNAKE_CASE = files["classy_state_dict"]["base_model"]["model"] __SCREAMING_SNAKE_CASE = model_state_dict["trunk"] model.load_state_dict(lowerCAmelCase_ ) return model.eval(), model_state_dict["heads"] # pretrained __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch" , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) __SCREAMING_SNAKE_CASE = partial( lowerCAmelCase_ , "https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch" , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowerCAmelCase_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowerCAmelCase_ , lowerCAmelCase_ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowerCAmelCase_ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , ) return config, expected_shape if __name__ == "__main__": a__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported regnet* architecture,''' ''' currently: regnetx-*, regnety-*. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) a__ : List[Any] = parser.parse_args() a__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
682
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging a__ : Any = logging.get_logger(__name__) class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" def __init__( self : Any , UpperCAmelCase__ : Union[str, Any]=None , **UpperCAmelCase__ : Union[str, Any] ) -> Any: warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , UpperCAmelCase__ , ) super().__init__(args=UpperCAmelCase__ , **UpperCAmelCase__ )
682
1