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
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): if len(__lowerCamelCase ) < k or k < 0: raise ValueError("Invalid Input" ) __snake_case : Optional[int] = sum(array[:k] ) for i in range(len(__lowerCamelCase ) - k ): __snake_case : Dict = current_sum - array[i] + array[i + k] __snake_case : int = max(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() _snake_case : Optional[Any] = [randint(-1_000, 1_000) for i in range(100)] _snake_case : Optional[int] = randint(0, 110) print(f'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
81
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
1
from __future__ import annotations import math def lowerCAmelCase_ ( __lowerCamelCase ): if num <= 0: __snake_case : Any = F'{num}: Invalid input, please enter a positive integer.' raise ValueError(__lowerCamelCase ) __snake_case : Union[str, Any] = [True] * (num + 1) __snake_case : int = [] __snake_case : List[str] = 2 __snake_case : Tuple = int(math.sqrt(__lowerCamelCase ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__lowerCamelCase ) # Set multiples of start be False for i in range(start * start , num + 1 , __lowerCamelCase ): if sieve[i] is True: __snake_case : Union[str, Any] = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__lowerCamelCase ) return prime if __name__ == "__main__": print(prime_sieve(int(input("Enter a positive integer: ").strip())))
81
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 a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).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() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).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() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = 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 __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = 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": __snake_case : Union[str, Any] = 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": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
1
import json import os import unittest from transformers import AutoTokenizer, GPTaTokenizer, GPTaTokenizerFast from transformers.models.gpta.tokenization_gpta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : int = GPTaTokenizer __UpperCAmelCase : Optional[int] = GPTaTokenizerFast __UpperCAmelCase : Optional[int] = True __UpperCAmelCase : List[str] = {"add_prefix_space": True} __UpperCAmelCase : int = False def __snake_case ( self : Union[str, Any] ) -> Dict: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __snake_case : int = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", "<|endoftext|>", ] __snake_case : Optional[Any] = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) ) __snake_case : Any = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] __snake_case : str = {"unk_token": "<unk>"} __snake_case : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __snake_case : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(lowerCamelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCamelCase ) ) def __snake_case ( self : str , **lowerCamelCase : int ) -> str: kwargs.update(self.special_tokens_map ) return GPTaTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase ) def __snake_case ( self : Dict , **lowerCamelCase : int ) -> Tuple: kwargs.update(self.special_tokens_map ) return GPTaTokenizerFast.from_pretrained(self.tmpdirname , **lowerCamelCase ) def __snake_case ( self : Optional[int] , lowerCamelCase : int ) -> Optional[int]: __snake_case : Dict = "lower newer" __snake_case : Optional[int] = "lower newer" return input_text, output_text def __snake_case ( self : List[Any] ) -> Dict: __snake_case : Dict = GPTaTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __snake_case : List[str] = "lower newer" __snake_case : int = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"] __snake_case : str = tokenizer.tokenize(lowerCamelCase , add_prefix_space=lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) __snake_case : Union[str, Any] = tokens + [tokenizer.unk_token] __snake_case : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[str]: if not self.test_rust_tokenizer: return __snake_case : Tuple = self.get_tokenizer() __snake_case : List[str] = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase ) __snake_case : str = "lower newer" # Testing tokenization __snake_case : Dict = tokenizer.tokenize(lowerCamelCase , add_prefix_space=lowerCamelCase ) __snake_case : List[Any] = rust_tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) # Testing conversion to ids without special tokens __snake_case : int = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase , add_prefix_space=lowerCamelCase ) __snake_case : int = rust_tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) # Testing conversion to ids with special tokens __snake_case : int = self.get_rust_tokenizer(add_prefix_space=lowerCamelCase ) __snake_case : int = tokenizer.encode(lowerCamelCase , add_prefix_space=lowerCamelCase ) __snake_case : str = rust_tokenizer.encode(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) # Testing the unknown token __snake_case : Optional[Any] = tokens + [rust_tokenizer.unk_token] __snake_case : str = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int , *lowerCamelCase : Dict , **lowerCamelCase : Dict ) -> Tuple: # It's very difficult to mix/test pretokenization with byte-level # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def __snake_case ( self : List[Any] , lowerCamelCase : str=15 ) -> str: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __snake_case : Any = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) # Simple input __snake_case : Tuple = "This is a simple input" __snake_case : Optional[int] = ["This is a simple input 1", "This is a simple input 2"] __snake_case : int = ("This is a simple input", "This is a pair") __snake_case : Optional[int] = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(lowerCamelCase , tokenizer_r.encode , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" ) # Simple input self.assertRaises(lowerCamelCase , tokenizer_r.encode_plus , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" ) # Simple input self.assertRaises( lowerCamelCase , tokenizer_r.batch_encode_plus , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" , ) # Pair input self.assertRaises(lowerCamelCase , tokenizer_r.encode , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" ) # Pair input self.assertRaises(lowerCamelCase , tokenizer_r.encode_plus , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" ) # Pair input self.assertRaises( lowerCamelCase , tokenizer_r.batch_encode_plus , lowerCamelCase , max_length=lowerCamelCase , padding="max_length" , ) def __snake_case ( self : Union[str, Any] ) -> int: __snake_case : int = GPTaTokenizer.from_pretrained(self.tmpdirname , pad_token="<pad>" ) # Simple input __snake_case : Any = "This is a simple input" __snake_case : int = ["This is a simple input looooooooong", "This is a simple input"] __snake_case : List[Any] = ("This is a simple input", "This is a pair") __snake_case : Any = [ ("This is a simple input loooooong", "This is a simple input"), ("This is a simple pair loooooong", "This is a simple pair"), ] __snake_case : Optional[Any] = tokenizer.pad_token_id __snake_case : Dict = tokenizer(lowerCamelCase , padding="max_length" , max_length=30 , return_tensors="np" ) __snake_case : Optional[Any] = tokenizer(lowerCamelCase , padding=lowerCamelCase , truncate=lowerCamelCase , return_tensors="np" ) __snake_case : List[Any] = tokenizer(*lowerCamelCase , padding="max_length" , max_length=60 , return_tensors="np" ) __snake_case : Union[str, Any] = tokenizer(lowerCamelCase , padding=lowerCamelCase , truncate=lowerCamelCase , return_tensors="np" ) # s # test single string max_length padding self.assertEqual(out_s["input_ids"].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s["input_ids"] ) self.assertTrue(0 in out_s["attention_mask"] ) # s2 # test automatic padding self.assertEqual(out_sa["input_ids"].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa["input_ids"][0] ) self.assertFalse(0 in out_sa["attention_mask"][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa["input_ids"][1] ) self.assertTrue(0 in out_sa["attention_mask"][1] ) # p # test single pair max_length padding self.assertEqual(out_p["input_ids"].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p["input_ids"] ) self.assertTrue(0 in out_p["attention_mask"] ) # p2 # test automatic padding pair self.assertEqual(out_pa["input_ids"].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa["input_ids"][0] ) self.assertFalse(0 in out_pa["attention_mask"][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa["input_ids"][1] ) self.assertTrue(0 in out_pa["attention_mask"][1] ) def __snake_case ( self : Optional[Any] ) -> Optional[Any]: __snake_case : List[str] = "$$$" __snake_case : int = GPTaTokenizer.from_pretrained(self.tmpdirname , bos_token=lowerCamelCase , add_bos_token=lowerCamelCase ) __snake_case : Union[str, Any] = "This is a simple input" __snake_case : List[Any] = ["This is a simple input 1", "This is a simple input 2"] __snake_case : Dict = tokenizer.bos_token_id __snake_case : List[Any] = tokenizer(lowerCamelCase ) __snake_case : Tuple = tokenizer(lowerCamelCase ) self.assertEqual(out_s.input_ids[0] , lowerCamelCase ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __snake_case : Tuple = tokenizer.decode(out_s.input_ids ) __snake_case : List[str] = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , lowerCamelCase ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) def __snake_case ( self : Dict ) -> Dict: pass def __snake_case ( self : Dict ) -> str: # TODO: change to self.get_tokenizers() when the fast version is implemented __snake_case : Optional[Any] = [self.get_tokenizer(do_lower_case=lowerCamelCase , add_bos_token=lowerCamelCase )] for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): __snake_case : Tuple = "Encode this." __snake_case : int = "This one too please." __snake_case : Tuple = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) encoded_sequence += tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) __snake_case : List[Any] = tokenizer.encode_plus( lowerCamelCase , lowerCamelCase , add_special_tokens=lowerCamelCase , return_special_tokens_mask=lowerCamelCase , ) __snake_case : Dict = encoded_sequence_dict["input_ids"] __snake_case : str = encoded_sequence_dict["special_tokens_mask"] self.assertEqual(len(lowerCamelCase ) , len(lowerCamelCase ) ) __snake_case : List[str] = [ (x if not special_tokens_mask[i] else None) for i, x in enumerate(lowerCamelCase ) ] __snake_case : Optional[Any] = [x for x in filtered_sequence if x is not None] self.assertEqual(lowerCamelCase , lowerCamelCase ) @require_tokenizers class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int ) -> List[Any]: # More context: # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1 # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519 # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439 __snake_case : Optional[int] = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=lowerCamelCase ) __snake_case : Optional[int] = "A photo of a cat" __snake_case : Union[str, Any] = tokenizer.encode( lowerCamelCase , ) self.assertEqual(lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained("test_opt" ) __snake_case : int = AutoTokenizer.from_pretrained("./test_opt" ) __snake_case : Tuple = tokenizer.encode( lowerCamelCase , ) self.assertEqual(lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) def __snake_case ( self : Union[str, Any] ) -> Tuple: __snake_case : Tuple = AutoTokenizer.from_pretrained("facebook/opt-350m" , use_slow=lowerCamelCase ) __snake_case : List[str] = "A photo of a cat" __snake_case : Dict = tokenizer.encode( lowerCamelCase , ) # Same as above self.assertEqual(lowerCamelCase , [2, 250, 1345, 9, 10, 4758] ) @unittest.skip("This test is failing because of a bug in the fast tokenizer" ) def __snake_case ( self : Optional[int] ) -> str: __snake_case : int = AutoTokenizer.from_pretrained("facebook/opt-350m" , from_slow=lowerCamelCase ) __snake_case : Any = "bos" __snake_case : str = tokenizer.get_vocab()["bos"] __snake_case : Any = "A photo of a cat" __snake_case : List[str] = tokenizer.encode( lowerCamelCase , ) # We changed the bos token self.assertEqual(lowerCamelCase , [31957, 250, 1345, 9, 10, 4758] ) tokenizer.save_pretrained("./tok" ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained("./tok" ) self.assertTrue(tokenizer.is_fast ) __snake_case : Optional[Any] = tokenizer.encode( lowerCamelCase , ) self.assertEqual(lowerCamelCase , [31957, 250, 1345, 9, 10, 4758] )
81
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _snake_case : Optional[int] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[Any] , *lowerCamelCase : Any , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
def lowerCAmelCase_ ( __lowerCamelCase ): assert isinstance(__lowerCamelCase , __lowerCamelCase ), F'The input value of [n={number}] is not an integer' if number == 1: return 2 elif number < 1: __snake_case : Dict = F'The input value of [n={number}] has to be > 0' raise ValueError(__lowerCamelCase ) else: __snake_case : Union[str, Any] = sylvester(number - 1 ) __snake_case : str = num - 1 __snake_case : List[Any] = num return lower * upper + 1 if __name__ == "__main__": print(f'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
81
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Any = SamImageProcessor() __snake_case : Optional[int] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Optional[int] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : int ) -> List[Any]: __snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[Any] ) -> Dict: __snake_case : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : List[str] ) -> Tuple: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Optional[int] = self.prepare_image_inputs() __snake_case : List[str] = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : Dict = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Tuple = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[str] = [torch.ones((1, 3, 5, 5) )] __snake_case : Tuple = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : int = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , torch.tensor(lowerCamelCase ) , torch.tensor(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : List[str] = [np.ones((1, 3, 5, 5) )] __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : str = [[1, 0], [0, 1]] with self.assertRaises(lowerCamelCase ): __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) @require_vision @require_tf class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : int = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : str , **lowerCamelCase : Any ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : Dict = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : int ) -> List[str]: __snake_case : List[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: __snake_case : str = self.get_image_processor() __snake_case : Union[str, Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : int = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : List[str] = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def __snake_case ( self : Any ) -> Optional[int]: __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Union[str, Any] = [tf.ones((1, 3, 5, 5) )] __snake_case : List[Any] = [[1764, 2646]] __snake_case : Dict = [[683, 1024]] __snake_case : List[str] = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , tf.convert_to_tensor(lowerCamelCase ) , tf.convert_to_tensor(lowerCamelCase ) , return_tensors="tf" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : Union[str, Any] = [np.ones((1, 3, 5, 5) )] __snake_case : List[str] = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Tuple = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __snake_case : Dict = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[str] , **lowerCamelCase : Any ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : str = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __snake_case : Dict = [tf.convert_to_tensor(lowerCamelCase )] __snake_case : List[Any] = [torch.tensor(lowerCamelCase )] __snake_case : Optional[Any] = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : Union[str, Any] = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) __snake_case : Dict = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : Any = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : Any = image_processor(lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Optional[Any] = processor(images=lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Tuple = image_processor(lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() __snake_case : List[Any] = processor(images=lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) )
81
1
def lowerCAmelCase_ ( __lowerCamelCase ): return str(__lowerCamelCase ) == str(__lowerCamelCase )[::-1] def lowerCAmelCase_ ( __lowerCamelCase ): return int(__lowerCamelCase ) + int(str(__lowerCamelCase )[::-1] ) def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0 ): __snake_case : Optional[int] = [] for num in range(1 , __lowerCamelCase ): __snake_case : str = 0 __snake_case : Optional[Any] = num while iterations < 5_0: __snake_case : Union[str, Any] = sum_reverse(__lowerCamelCase ) iterations += 1 if is_palindrome(__lowerCamelCase ): break else: lychrel_nums.append(__lowerCamelCase ) return len(__lowerCamelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
81
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowerCamelCase : str , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : int = abs(__lowerCamelCase ) __snake_case : Dict = 0 while n > 0: res += n % 1_0 n //= 1_0 return res def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Union[str, Any] = abs(__lowerCamelCase ) return n if n < 1_0 else n % 1_0 + sum_of_digits(n // 1_0 ) def lowerCAmelCase_ ( __lowerCamelCase ): return sum(int(__lowerCamelCase ) for c in str(abs(__lowerCamelCase ) ) ) def lowerCAmelCase_ ( ): from collections.abc import Callable from timeit import timeit def benchmark_a_function(__lowerCamelCase , __lowerCamelCase ) -> None: __snake_case : Optional[Any] = F'{func.__name__}({value})' __snake_case : List[str] = timeit(F'__main__.{call}' , setup="import __main__" ) print(F'{call:56} = {func(__lowerCamelCase )} -- {timing:.4f} seconds' ) for value in (2_6_2_1_4_4, 1_1_2_5_8_9_9_9_0_6_8_4_2_6_2_4, 1_2_6_7_6_5_0_6_0_0_2_2_8_2_2_9_4_0_1_4_9_6_7_0_3_2_0_5_3_7_6): for func in (sum_of_digits, sum_of_digits_recursion, sum_of_digits_compact): benchmark_a_function(__lowerCamelCase , __lowerCamelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
81
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case : Union[str, Any] = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["OwlViTFeatureExtractor"] _snake_case : Optional[int] = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _snake_case : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available _snake_case : Optional[int] = {"tokenization_herbert": ["HerbertTokenizer"]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Any = ["HerbertTokenizerFast"] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys _snake_case : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : str = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "van" def __init__( self : Optional[int] , lowerCamelCase : Any=224 , lowerCamelCase : str=3 , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : Dict=[4, 2, 2, 2] , lowerCamelCase : List[Any]=[64, 128, 320, 512] , lowerCamelCase : str=[3, 3, 12, 3] , lowerCamelCase : Dict=[8, 8, 4, 4] , lowerCamelCase : Any="gelu" , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Tuple=1E-6 , lowerCamelCase : Optional[int]=1E-2 , lowerCamelCase : int=0.0 , lowerCamelCase : Optional[Any]=0.0 , **lowerCamelCase : Optional[int] , ) -> int: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = image_size __snake_case : Any = num_channels __snake_case : Any = patch_sizes __snake_case : List[Any] = strides __snake_case : str = hidden_sizes __snake_case : Dict = depths __snake_case : Optional[int] = mlp_ratios __snake_case : Dict = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : Optional[int] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : int = dropout_rate
81
1
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Any = (UnCLIPScheduler,) def __snake_case ( self : Dict , **lowerCamelCase : int ) -> Optional[Any]: __snake_case : Union[str, Any] = { "num_train_timesteps": 1000, "variance_type": "fixed_small_log", "clip_sample": True, "clip_sample_range": 1.0, "prediction_type": "epsilon", } config.update(**lowerCamelCase ) return config def __snake_case ( self : Any ) -> str: for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> Optional[Any]: for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> str: for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowerCamelCase ) def __snake_case ( self : int ) -> Union[str, Any]: for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Any: for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=lowerCamelCase ) def __snake_case ( self : List[Any] ) -> List[Any]: for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=lowerCamelCase , prev_timestep=lowerCamelCase ) def __snake_case ( self : int ) -> Optional[Any]: __snake_case : Union[str, Any] = self.scheduler_classes[0] __snake_case : List[str] = self.get_scheduler_config(variance_type="fixed_small_log" ) __snake_case : Any = scheduler_class(**lowerCamelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 1.0000E-10 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 ) - 0.0_54_96_25 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 ) - 0.9_99_49_87 ) ) < 1E-5 def __snake_case ( self : Optional[Any] ) -> Tuple: __snake_case : Optional[Any] = self.scheduler_classes[0] __snake_case : Tuple = self.get_scheduler_config(variance_type="learned_range" ) __snake_case : Any = scheduler_class(**lowerCamelCase ) __snake_case : Optional[Any] = 0.5 assert scheduler._get_variance(1 , predicted_variance=lowerCamelCase ) - -10.1_71_27_90 < 1E-5 assert scheduler._get_variance(487 , predicted_variance=lowerCamelCase ) - -5.7_99_80_52 < 1E-5 assert scheduler._get_variance(999 , predicted_variance=lowerCamelCase ) - -0.0_01_00_11 < 1E-5 def __snake_case ( self : int ) -> int: __snake_case : Tuple = self.scheduler_classes[0] __snake_case : Union[str, Any] = self.get_scheduler_config() __snake_case : Tuple = scheduler_class(**lowerCamelCase ) __snake_case : Optional[int] = scheduler.timesteps __snake_case : List[Any] = self.dummy_model() __snake_case : str = self.dummy_sample_deter __snake_case : Union[str, Any] = torch.manual_seed(0 ) for i, t in enumerate(lowerCamelCase ): # 1. predict noise residual __snake_case : Union[str, Any] = model(lowerCamelCase , lowerCamelCase ) # 2. predict previous mean of sample x_t-1 __snake_case : str = scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , generator=lowerCamelCase ).prev_sample __snake_case : List[str] = pred_prev_sample __snake_case : Tuple = torch.sum(torch.abs(lowerCamelCase ) ) __snake_case : List[str] = torch.mean(torch.abs(lowerCamelCase ) ) assert abs(result_sum.item() - 2_52.2_68_24_95 ) < 1E-2 assert abs(result_mean.item() - 0.3_28_47_43 ) < 1E-3 def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Union[str, Any] = self.scheduler_classes[0] __snake_case : str = self.get_scheduler_config() __snake_case : int = scheduler_class(**lowerCamelCase ) scheduler.set_timesteps(25 ) __snake_case : str = scheduler.timesteps __snake_case : List[Any] = self.dummy_model() __snake_case : Tuple = self.dummy_sample_deter __snake_case : int = torch.manual_seed(0 ) for i, t in enumerate(lowerCamelCase ): # 1. predict noise residual __snake_case : Dict = model(lowerCamelCase , lowerCamelCase ) if i + 1 == timesteps.shape[0]: __snake_case : Dict = None else: __snake_case : List[str] = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 __snake_case : int = scheduler.step( lowerCamelCase , lowerCamelCase , lowerCamelCase , prev_timestep=lowerCamelCase , generator=lowerCamelCase ).prev_sample __snake_case : Union[str, Any] = pred_prev_sample __snake_case : List[str] = torch.sum(torch.abs(lowerCamelCase ) ) __snake_case : Union[str, Any] = torch.mean(torch.abs(lowerCamelCase ) ) assert abs(result_sum.item() - 2_58.2_04_49_83 ) < 1E-2 assert abs(result_mean.item() - 0.3_36_20_38 ) < 1E-3 def __snake_case ( self : int ) -> Any: pass def __snake_case ( self : Union[str, Any] ) -> Optional[int]: pass
81
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case : Union[str, Any] = logging.getLogger(__name__) def lowerCAmelCase_ ( ): __snake_case : int = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __snake_case : List[str] = parser.parse_args() return args def lowerCAmelCase_ ( __lowerCamelCase ): def fn(__lowerCamelCase ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = [] for i in range(len(tokenized_data["input_ids"] ) ): __snake_case : Tuple = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase ) __snake_case : str = tf.train.Example(features=__lowerCamelCase ) __snake_case : List[str] = example.SerializeToString() records.append(__lowerCamelCase ) return records def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) __snake_case : Dict = dataset.select(range(__lowerCamelCase ) ) print(F'Limiting the dataset to {args.limit} entries.' ) __snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __snake_case : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: __snake_case : str = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __snake_case : Any = tokenize_function(__lowerCamelCase ) __snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__lowerCamelCase ): # Concatenate all texts. __snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()} __snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __snake_case : int = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result __snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 ) __snake_case : Optional[Any] = 0 __snake_case : Optional[Any] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): __snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size] __snake_case : Any = len(dataset_snapshot["input_ids"] ) __snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' ) __snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): __snake_case : Union[str, Any] = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase ) if __name__ == "__main__": _snake_case : List[Any] = parse_args() main(args)
81
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case : Dict = logging.get_logger(__name__) _snake_case : Dict = { "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json", "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json", "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json", "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json", "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json", "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json", "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json", "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json", "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json", } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = "xmod" def __init__( self : Tuple , lowerCamelCase : Any=30522 , lowerCamelCase : Union[str, Any]=768 , lowerCamelCase : Union[str, Any]=12 , lowerCamelCase : List[str]=12 , lowerCamelCase : List[Any]=3072 , lowerCamelCase : List[Any]="gelu" , lowerCamelCase : Union[str, Any]=0.1 , lowerCamelCase : Dict=0.1 , lowerCamelCase : Any=512 , lowerCamelCase : Any=2 , lowerCamelCase : List[str]=0.02 , lowerCamelCase : Union[str, Any]=1E-12 , lowerCamelCase : List[Any]=1 , lowerCamelCase : Union[str, Any]=0 , lowerCamelCase : List[str]=2 , lowerCamelCase : List[str]="absolute" , lowerCamelCase : Dict=True , lowerCamelCase : List[Any]=None , lowerCamelCase : Union[str, Any]=False , lowerCamelCase : int=2 , lowerCamelCase : Union[str, Any]=False , lowerCamelCase : List[Any]=True , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[Any]=("en_XX",) , lowerCamelCase : List[Any]=None , **lowerCamelCase : Union[str, Any] , ) -> Optional[Any]: super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase ) __snake_case : Union[str, Any] = vocab_size __snake_case : List[Any] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : Tuple = num_attention_heads __snake_case : List[str] = hidden_act __snake_case : Optional[int] = intermediate_size __snake_case : Optional[int] = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : Any = max_position_embeddings __snake_case : Optional[Any] = type_vocab_size __snake_case : List[Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : str = position_embedding_type __snake_case : int = use_cache __snake_case : List[str] = classifier_dropout __snake_case : Tuple = pre_norm __snake_case : Any = adapter_reduction_factor __snake_case : str = adapter_layer_norm __snake_case : Optional[Any] = adapter_reuse_layer_norm __snake_case : List[Any] = ln_before_adapter __snake_case : List[str] = list(lowerCamelCase ) __snake_case : int = default_language class a (_lowerCAmelCase ): """simple docstring""" @property def __snake_case ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __snake_case : Dict = {0: "batch", 1: "choice", 2: "sequence"} else: __snake_case : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
81
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _snake_case : List[Any] = "\\n Text data.\n Second line of data." _snake_case : Tuple = "file" @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") __snake_case : Optional[Any] = bytes(__lowerCamelCase , "utf-8" ) with zstd.open(__lowerCamelCase , "wb" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture def lowerCAmelCase_ ( __lowerCamelCase ): with open(os.path.join(tmpfs.local_root_dir , __lowerCamelCase ) , "w" ) as f: f.write(__lowerCamelCase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} __snake_case : str = input_paths[compression_format] __snake_case : Optional[Any] = tmp_path / "cache" __snake_case : Optional[int] = DownloadConfig(cache_dir=__lowerCamelCase , extract_compressed_file=__lowerCamelCase ) __snake_case : Union[str, Any] = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) with open(__lowerCamelCase ) as f: __snake_case : Dict = f.read() with open(__lowerCamelCase ) as f: __snake_case : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = "custom_cache" __snake_case : List[str] = "custom_extracted_dir" __snake_case : Any = tmp_path / "custom_extracted_path" if default_extracted: __snake_case : List[Any] = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __lowerCamelCase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__lowerCamelCase ) ) __snake_case : Optional[Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __snake_case : Optional[int] = xz_file __snake_case : Optional[int] = ( DownloadConfig(extract_compressed_file=__lowerCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__lowerCamelCase ) ) __snake_case : str = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) assert Path(__lowerCamelCase ).parent.parts[-2:] == expected def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : Optional[Any] = str(Path(__lowerCamelCase ).resolve() ) assert cached_path(__lowerCamelCase ) == text_file # relative path __snake_case : Any = str(Path(__lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(__lowerCamelCase ) == text_file def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) # relative path __snake_case : Optional[int] = "./__missing_file__.txt" with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : str = get_from_cache(F'tmp://{tmpfs_file}' ) with open(__lowerCamelCase ) as f: __snake_case : Union[str, Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( ): with pytest.raises(__lowerCamelCase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): http_get("https://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[str] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): ftp_get("ftp://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): fsspec_get("s3://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): fsspec_head("s3://huggingface.co" )
81
1
from math import atan, cos, radians, sin, tan from .haversine_distance import haversine_distance _snake_case : List[Any] = 6_37_81_37.0 _snake_case : int = 6_35_67_52.31_42_45 _snake_case : Dict = 6_378_137 def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = (AXIS_A - AXIS_B) / AXIS_A # Parametric latitudes # https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude __snake_case : Tuple = atan((1 - flattening) * tan(radians(__lowerCamelCase ) ) ) __snake_case : List[Any] = atan((1 - flattening) * tan(radians(__lowerCamelCase ) ) ) # Compute central angle between two points # using haversine theta. sigma = haversine_distance / equatorial radius __snake_case : Union[str, Any] = haversine_distance(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) / EQUATORIAL_RADIUS # Intermediate P and Q values __snake_case : Tuple = (b_lata + b_lata) / 2 __snake_case : Union[str, Any] = (b_lata - b_lata) / 2 # Intermediate X value # X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2) __snake_case : Tuple = (sin(__lowerCamelCase ) ** 2) * (cos(__lowerCamelCase ) ** 2) __snake_case : Union[str, Any] = cos(sigma / 2 ) ** 2 __snake_case : Optional[int] = (sigma - sin(__lowerCamelCase )) * (x_numerator / x_demonimator) # Intermediate Y value # Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2) __snake_case : int = (cos(__lowerCamelCase ) ** 2) * (sin(__lowerCamelCase ) ** 2) __snake_case : Tuple = sin(sigma / 2 ) ** 2 __snake_case : Any = (sigma + sin(__lowerCamelCase )) * (y_numerator / y_denominator) return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value))) if __name__ == "__main__": import doctest doctest.testmod()
81
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = start # add current to visited visited.append(__lowerCamelCase ) __snake_case : List[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __snake_case : Tuple = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # if all neighbors visited add current to sort sort.append(__lowerCamelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCamelCase ) != len(__lowerCamelCase ): for vertice in vertices: if vertice not in visited: __snake_case : int = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # return sort return sort if __name__ == "__main__": _snake_case : List[Any] = topological_sort("a", [], []) print(sort)
81
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Tuple = logging.get_logger(__name__) _snake_case : List[Any] = { "microsoft/cvt-13": "https://huggingface.co/microsoft/cvt-13/resolve/main/config.json", # See all Cvt models at https://huggingface.co/models?filter=cvt } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "cvt" def __init__( self : Optional[int] , lowerCamelCase : Union[str, Any]=3 , lowerCamelCase : Any=[7, 3, 3] , lowerCamelCase : str=[4, 2, 2] , lowerCamelCase : List[str]=[2, 1, 1] , lowerCamelCase : List[Any]=[64, 192, 384] , lowerCamelCase : List[str]=[1, 3, 6] , lowerCamelCase : Dict=[1, 2, 10] , lowerCamelCase : Any=[4.0, 4.0, 4.0] , lowerCamelCase : List[Any]=[0.0, 0.0, 0.0] , lowerCamelCase : Any=[0.0, 0.0, 0.0] , lowerCamelCase : List[Any]=[0.0, 0.0, 0.1] , lowerCamelCase : Tuple=[True, True, True] , lowerCamelCase : Tuple=[False, False, True] , lowerCamelCase : Tuple=["dw_bn", "dw_bn", "dw_bn"] , lowerCamelCase : Dict=[3, 3, 3] , lowerCamelCase : Dict=[1, 1, 1] , lowerCamelCase : str=[2, 2, 2] , lowerCamelCase : Union[str, Any]=[1, 1, 1] , lowerCamelCase : List[str]=[1, 1, 1] , lowerCamelCase : Dict=0.02 , lowerCamelCase : Optional[int]=1E-12 , **lowerCamelCase : Union[str, Any] , ) -> Optional[int]: super().__init__(**lowerCamelCase ) __snake_case : Dict = num_channels __snake_case : Any = patch_sizes __snake_case : Dict = patch_stride __snake_case : Dict = patch_padding __snake_case : Any = embed_dim __snake_case : Union[str, Any] = num_heads __snake_case : List[str] = depth __snake_case : str = mlp_ratio __snake_case : Union[str, Any] = attention_drop_rate __snake_case : Optional[Any] = drop_rate __snake_case : Tuple = drop_path_rate __snake_case : List[Any] = qkv_bias __snake_case : List[Any] = cls_token __snake_case : int = qkv_projection_method __snake_case : str = kernel_qkv __snake_case : Dict = padding_kv __snake_case : List[str] = stride_kv __snake_case : int = padding_q __snake_case : str = stride_q __snake_case : int = initializer_range __snake_case : Optional[int] = layer_norm_eps
81
def lowerCAmelCase_ ( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(__lowerCamelCase , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
81
1
import tempfile import unittest from pathlib import Path from shutil import copyfile from transformers import MaMaaaTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from transformers.utils import is_sentencepiece_available if is_sentencepiece_available(): from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json from ...test_tokenization_common import TokenizerTesterMixin if is_sentencepiece_available(): _snake_case : List[str] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right _snake_case : Optional[Any] = 128_022 _snake_case : Optional[Any] = 128_028 @require_sentencepiece class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Dict = MaMaaaTokenizer __UpperCAmelCase : Tuple = False __UpperCAmelCase : Optional[Any] = False __UpperCAmelCase : Dict = True def __snake_case ( self : Union[str, Any] ) -> int: super().setUp() __snake_case : Optional[Any] = ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"] __snake_case : List[Any] = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) ) __snake_case : Dict = Path(self.tmpdirname ) save_json(lowerCamelCase , save_dir / VOCAB_FILES_NAMES["vocab_file"] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(lowerCamelCase , save_dir / VOCAB_FILES_NAMES["spm_file"] ) __snake_case : Any = MaMaaaTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Dict ) -> Tuple: return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **lowerCamelCase ) def __snake_case ( self : Any , lowerCamelCase : str ) -> List[Any]: return ( "This is a test", "This is a test", ) def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = "</s>" __snake_case : int = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase ) , lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : str ) -> str: __snake_case : Tuple = self.get_tokenizer() __snake_case : str = list(tokenizer.get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "</s>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "<s>" ) self.assertEqual(len(lowerCamelCase ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) ) @unittest.skip("Skip this test while all models are still to be uploaded." ) def __snake_case ( self : Dict ) -> str: pass def __snake_case ( self : Any ) -> Any: __snake_case : Any = self.get_tokenizer() __snake_case : List[Any] = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase ) , [2, 3, 4, 5, 6] , ) __snake_case : Dict = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] ) self.assertListEqual(lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) __snake_case : Optional[Any] = tokenizer.convert_tokens_to_string(lowerCamelCase ) self.assertEqual(lowerCamelCase , "This is a test" ) @slow def __snake_case ( self : Optional[int] ) -> Optional[Any]: # fmt: off __snake_case : List[str] = {"input_ids": [[128022, 110108, 397, 11, 38272, 2247, 124811, 285, 18105, 1586, 207, 7, 39534, 4428, 397, 1019, 18105, 1586, 207, 7, 41337, 16786, 241, 7, 20214, 17, 125690, 10398, 7, 44378, 58069, 68342, 7798, 7343, 11, 299, 33310, 4, 158, 37350, 94077, 4569, 299, 33310, 90, 4, 52840, 290, 4, 31270, 112, 299, 682, 4, 52840, 39953, 14079, 193, 52519, 90894, 17894, 120697, 11, 40445, 551, 17, 1019, 52519, 90894, 17756, 963, 11, 40445, 480, 17, 9792, 1120, 5173, 1393, 6240, 16786, 241, 120996, 28, 1245, 1393, 118240, 11123, 1019, 93612, 2691, 10618, 98058, 120409, 1928, 279, 4, 40683, 367, 178, 207, 1019, 103, 103121, 506, 65296, 5, 2], [128022, 21217, 367, 117, 125450, 128, 719, 7, 7308, 40, 93612, 12669, 1116, 16704, 71, 17785, 3699, 15592, 35, 144, 9584, 241, 11943, 713, 950, 799, 2247, 88427, 150, 149, 118813, 120706, 1019, 106906, 81518, 28, 1224, 22799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [128022, 1658, 123311, 5155, 5578, 4722, 279, 14947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase , model_name="facebook/m2m100_418M" , revision="c168bae485c864188cf9aa0e4108b0b6934dc91e" , ) @require_torch @require_sentencepiece @require_tokenizers class a (unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = "facebook/m2m100_418M" __UpperCAmelCase : Optional[Any] = [ "In my opinion, there are two levels of response from the French government.", "NSA Affair Emphasizes Complete Lack of Debate on Intelligence", ] __UpperCAmelCase : Dict = [ "Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.", "L'affaire NSA souligne l'absence totale de débat sur le renseignement", ] # fmt: off __UpperCAmelCase : Optional[Any] = [EN_CODE, 593, 1949, 11_5781, 4, 7_1586, 4234, 6_0633, 12_6233, 432, 12_3808, 1_5592, 1197, 11_7132, 12_0618, 5, 2] @classmethod def __snake_case ( cls : Tuple ) -> int: __snake_case : MaMaaaTokenizer = MaMaaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en" , tgt_lang="fr" ) __snake_case : Optional[Any] = 1 return cls def __snake_case ( self : Optional[Any] ) -> Dict: self.assertEqual(self.tokenizer.get_lang_id("ar" ) , 128006 ) self.assertEqual(self.tokenizer.get_lang_id("en" ) , 128022 ) self.assertEqual(self.tokenizer.get_lang_id("ro" ) , 128076 ) self.assertEqual(self.tokenizer.get_lang_id("mr" ) , 128063 ) def __snake_case ( self : Tuple ) -> List[str]: __snake_case : List[str] = self.tokenizer.get_vocab() self.assertEqual(len(lowerCamelCase ) , self.tokenizer.vocab_size ) self.assertEqual(vocab["<unk>"] , 3 ) self.assertIn(self.tokenizer.get_lang_token("en" ) , lowerCamelCase ) def __snake_case ( self : Tuple ) -> int: __snake_case : str = "en" __snake_case : Any = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowerCamelCase ) def __snake_case ( self : Dict ) -> str: self.assertIn(lowerCamelCase , self.tokenizer.all_special_ids ) # fmt: off __snake_case : Any = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 14028, 136, 3286, 9706, 6, 90797, 6, 144012, 162, 88128, 30061, 5, 2] # fmt: on __snake_case : Any = self.tokenizer.decode(lowerCamelCase , skip_special_tokens=lowerCamelCase ) __snake_case : Optional[Any] = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , lowerCamelCase ) def __snake_case ( self : int ) -> int: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Optional[Any] = self.tokenizer.lang_token_to_id self.tokenizer.save_pretrained(lowerCamelCase ) __snake_case : Optional[Any] = MaMaaaTokenizer.from_pretrained(lowerCamelCase ) self.assertDictEqual(new_tok.lang_token_to_id , lowerCamelCase ) @require_torch def __snake_case ( self : List[str] ) -> str: __snake_case : Tuple = "en" __snake_case : List[str] = "fr" __snake_case : Any = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowerCamelCase , return_tensors="pt" ) __snake_case : Union[str, Any] = shift_tokens_right( batch["labels"] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id ) for k in batch: __snake_case : str = batch[k].tolist() # batch = {k: v.tolist() for k,v in batch.items()} # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 # batch.decoder_inputs_ids[0][0] == assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == FR_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2] == [2, FR_CODE] @require_torch def __snake_case ( self : str ) -> List[str]: __snake_case : Any = "mr" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) __snake_case : Tuple = "zh" self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) @require_torch def __snake_case ( self : Optional[Any] ) -> int: __snake_case : Optional[Any] = "mr" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("mr" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) __snake_case : Dict = "zh" self.tokenizer._switch_to_target_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id("zh" )] ) self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) self.tokenizer._switch_to_input_mode() self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] ) @require_torch def __snake_case ( self : List[str] ) -> List[Any]: __snake_case : List[Any] = self.tokenizer._build_translation_inputs("A test" , return_tensors="pt" , src_lang="en" , tgt_lang="ar" ) self.assertEqual( nested_simplify(lowerCamelCase ) , { # en_XX, A, test, EOS "input_ids": [[128022, 58, 4183, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 128006, } , )
81
from math import sqrt def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0_0_0 ): __snake_case : int = 0 __snake_case : int = 0 __snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__lowerCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
81
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case : List[Any] = logging.get_logger(__name__) _snake_case : Optional[int] = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = "big_bird" def __init__( self : Union[str, Any] , lowerCamelCase : Union[str, Any]=50358 , lowerCamelCase : List[str]=768 , lowerCamelCase : Any=12 , lowerCamelCase : List[str]=12 , lowerCamelCase : Any=3072 , lowerCamelCase : Optional[Any]="gelu_new" , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : int=0.1 , lowerCamelCase : str=4096 , lowerCamelCase : Optional[Any]=2 , lowerCamelCase : Dict=0.02 , lowerCamelCase : int=1E-12 , lowerCamelCase : Dict=True , lowerCamelCase : Union[str, Any]=0 , lowerCamelCase : List[str]=1 , lowerCamelCase : str=2 , lowerCamelCase : Tuple=66 , lowerCamelCase : Dict="block_sparse" , lowerCamelCase : List[str]=True , lowerCamelCase : Dict=False , lowerCamelCase : str=64 , lowerCamelCase : List[Any]=3 , lowerCamelCase : List[Any]=None , **lowerCamelCase : Union[str, Any] , ) -> str: super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __snake_case : Optional[int] = vocab_size __snake_case : Any = max_position_embeddings __snake_case : int = hidden_size __snake_case : List[str] = num_hidden_layers __snake_case : int = num_attention_heads __snake_case : Dict = intermediate_size __snake_case : str = hidden_act __snake_case : List[str] = hidden_dropout_prob __snake_case : str = attention_probs_dropout_prob __snake_case : Optional[int] = initializer_range __snake_case : Any = type_vocab_size __snake_case : List[Any] = layer_norm_eps __snake_case : Optional[Any] = use_cache __snake_case : List[Any] = rescale_embeddings __snake_case : int = attention_type __snake_case : int = use_bias __snake_case : List[str] = block_size __snake_case : Tuple = num_random_blocks __snake_case : Union[str, Any] = classifier_dropout class a (_lowerCAmelCase ): """simple docstring""" @property def __snake_case ( self : Dict ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __snake_case : str = {0: "batch", 1: "choice", 2: "sequence"} else: __snake_case : Optional[Any] = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
81
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : str ) -> str: __snake_case : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "neck_hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) ) class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Tuple=13 , lowerCamelCase : str=32 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=3 , lowerCamelCase : Any=640 , lowerCamelCase : Optional[Any]=4 , lowerCamelCase : Tuple="silu" , lowerCamelCase : int=3 , lowerCamelCase : Dict=32 , lowerCamelCase : str=0.1 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=0.02 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=10 , lowerCamelCase : int=None , ) -> str: __snake_case : Optional[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Any = image_size __snake_case : List[Any] = patch_size __snake_case : Any = num_channels __snake_case : Union[str, Any] = last_hidden_size __snake_case : Any = num_attention_heads __snake_case : Any = hidden_act __snake_case : Tuple = conv_kernel_size __snake_case : Any = output_stride __snake_case : Any = hidden_dropout_prob __snake_case : List[Any] = attention_probs_dropout_prob __snake_case : Optional[Any] = classifier_dropout_prob __snake_case : Union[str, Any] = use_labels __snake_case : Optional[int] = is_training __snake_case : Dict = num_labels __snake_case : Any = initializer_range __snake_case : Optional[int] = scope def __snake_case ( self : str ) -> Union[str, Any]: __snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : List[Any] = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __snake_case : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case ( self : Any ) -> Union[str, Any]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] ) -> Dict: __snake_case : List[Any] = MobileViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[str] = model(lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ) -> List[str]: __snake_case : str = self.num_labels __snake_case : List[Any] = MobileViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Dict: __snake_case : Union[str, Any] = self.num_labels __snake_case : Optional[int] = MobileViTForSemanticSegmentation(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Tuple = model(lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[int] ) -> List[Any]: __snake_case : Optional[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = config_and_inputs __snake_case : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Optional[Any] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Optional[int] = False def __snake_case ( self : Optional[int] ) -> Dict: __snake_case : Tuple = MobileViTModelTester(self ) __snake_case : Any = MobileViTConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds" ) def __snake_case ( self : Dict ) -> Any: pass @unittest.skip(reason="MobileViT does not support input and output embeddings" ) def __snake_case ( self : Dict ) -> List[Any]: pass @unittest.skip(reason="MobileViT does not output attentions" ) def __snake_case ( self : int ) -> Dict: pass def __snake_case ( self : int ) -> Union[str, Any]: __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = model_class(lowerCamelCase ) __snake_case : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __snake_case ( self : int ) -> Tuple: pass def __snake_case ( self : Any ) -> Tuple: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : Any ) -> str: def check_hidden_states_output(lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any ): __snake_case : int = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __snake_case : int = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __snake_case : Union[str, Any] = outputs.hidden_states __snake_case : int = 5 self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __snake_case : List[Any] = 2 for i in range(len(lowerCamelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __snake_case , __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : List[Any] = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Any ) -> Any: __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> List[str]: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase ) @slow def __snake_case ( self : List[str] ) -> Any: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = MobileViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def lowerCAmelCase_ ( ): __snake_case : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a (unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : str ) -> Dict: return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None @slow def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : Tuple = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowerCamelCase ) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Dict = model(**lowerCamelCase ) # verify the logits __snake_case : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : str ) -> Optional[int]: __snake_case : Optional[int] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : str = model.to(lowerCamelCase ) __snake_case : int = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Optional[int] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : List[str] = model(**lowerCamelCase ) __snake_case : Union[str, Any] = outputs.logits # verify the logits __snake_case : Tuple = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , lowerCamelCase ) __snake_case : Union[str, Any] = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ] , device=lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : Union[str, Any] ) -> Optional[int]: __snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Tuple = model.to(lowerCamelCase ) __snake_case : Dict = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Any = model(**lowerCamelCase ) __snake_case : Dict = outputs.logits.detach().cpu() __snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(50, 60)] ) __snake_case : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , lowerCamelCase ) __snake_case : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ) __snake_case : Optional[int] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , lowerCamelCase )
81
1
import unittest from transformers import ( MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TextClassificationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow from .test_pipelines_common import ANY # These 2 model types require different inputs than those of the usual text models. _snake_case : List[Any] = {"LayoutLMv2Config", "LayoutLMv3Config"} @is_pipeline_test class a (unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Tuple = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING __UpperCAmelCase : str = TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if model_mapping is not None: __UpperCAmelCase : Any = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP} if tf_model_mapping is not None: __UpperCAmelCase : str = { config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP } @require_torch def __snake_case ( self : Tuple ) -> List[Any]: __snake_case : Tuple = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="pt" ) __snake_case : int = text_classifier("This is great !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}] ) __snake_case : List[Any] = text_classifier("This is great !" , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}] ) __snake_case : int = text_classifier(["This is great !", "This is bad"] , top_k=2 ) self.assertEqual( nested_simplify(lowerCamelCase ) , [ [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}], [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}], ] , ) __snake_case : int = text_classifier("This is great !" , top_k=1 ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}] ) # Legacy behavior __snake_case : str = text_classifier("This is great !" , return_all_scores=lowerCamelCase ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}] ) __snake_case : str = text_classifier("This is great !" , return_all_scores=lowerCamelCase ) self.assertEqual( nested_simplify(lowerCamelCase ) , [[{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}]] ) __snake_case : Optional[int] = text_classifier(["This is great !", "Something else"] , return_all_scores=lowerCamelCase ) self.assertEqual( nested_simplify(lowerCamelCase ) , [ [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}], [{"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_1", "score": 0.4_96}], ] , ) __snake_case : str = text_classifier(["This is great !", "Something else"] , return_all_scores=lowerCamelCase ) self.assertEqual( nested_simplify(lowerCamelCase ) , [ {"label": "LABEL_0", "score": 0.5_04}, {"label": "LABEL_0", "score": 0.5_04}, ] , ) @require_torch def __snake_case ( self : Optional[Any] ) -> str: import torch __snake_case : Any = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="pt" , device=torch.device("cpu" ) , ) __snake_case : Any = text_classifier("This is great !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}] ) @require_tf def __snake_case ( self : List[str] ) -> List[Any]: __snake_case : Any = pipeline( task="text-classification" , model="hf-internal-testing/tiny-random-distilbert" , framework="tf" ) __snake_case : List[Any] = text_classifier("This is great !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "LABEL_0", "score": 0.5_04}] ) @slow @require_torch def __snake_case ( self : Dict ) -> Dict: __snake_case : Optional[Any] = pipeline("text-classification" ) __snake_case : Optional[Any] = text_classifier("This is great !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "POSITIVE", "score": 1.0}] ) __snake_case : Tuple = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "NEGATIVE", "score": 1.0}] ) __snake_case : List[str] = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "POSITIVE", "score": 0.9_88}] ) @slow @require_tf def __snake_case ( self : Tuple ) -> Dict: __snake_case : Tuple = pipeline("text-classification" , framework="tf" ) __snake_case : int = text_classifier("This is great !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "POSITIVE", "score": 1.0}] ) __snake_case : Dict = text_classifier("This is bad !" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "NEGATIVE", "score": 1.0}] ) __snake_case : Dict = text_classifier("Birds are a type of animal" ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": "POSITIVE", "score": 0.9_88}] ) def __snake_case ( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : Dict , lowerCamelCase : int ) -> Dict: __snake_case : List[str] = TextClassificationPipeline(model=lowerCamelCase , tokenizer=lowerCamelCase ) return text_classifier, ["HuggingFace is in", "This is another test"] def __snake_case ( self : Optional[int] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict ) -> List[Any]: __snake_case : List[str] = text_classifier.model # Small inputs because BartTokenizer tiny has maximum position embeddings = 22 __snake_case : List[str] = "HuggingFace is in" __snake_case : str = text_classifier(lowerCamelCase ) self.assertEqual(nested_simplify(lowerCamelCase ) , [{"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}] ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) __snake_case : Any = ["HuggingFace is in ", "Paris is in France"] __snake_case : Any = text_classifier(lowerCamelCase ) self.assertEqual( nested_simplify(lowerCamelCase ) , [{"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}, {"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}] , ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() ) self.assertTrue(outputs[1]["label"] in model.config.idalabel.values() ) # Forcing to get all results with `top_k=None` # This is NOT the legacy format __snake_case : List[str] = text_classifier(lowerCamelCase , top_k=lowerCamelCase ) __snake_case : List[Any] = len(model.config.idalabel.values() ) self.assertEqual( nested_simplify(lowerCamelCase ) , [[{"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}] * N, [{"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}] * N] , ) __snake_case : Any = {"text": "HuggingFace is in ", "text_pair": "Paris is in France"} __snake_case : List[Any] = text_classifier(lowerCamelCase ) self.assertEqual( nested_simplify(lowerCamelCase ) , {"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )} , ) self.assertTrue(outputs["label"] in model.config.idalabel.values() ) # This might be used a text pair, but tokenizer + pipe interaction # makes it hard to understand that it's not using the pair properly # https://github.com/huggingface/transformers/issues/17305 # We disabled this usage instead as it was outputting wrong outputs. __snake_case : Dict = [["HuggingFace is in ", "Paris is in France"]] with self.assertRaises(lowerCamelCase ): text_classifier(lowerCamelCase ) # This used to be valid for doing text pairs # We're keeping it working because of backward compatibility __snake_case : Optional[int] = text_classifier([[["HuggingFace is in ", "Paris is in France"]]] ) self.assertEqual( nested_simplify(lowerCamelCase ) , [{"label": ANY(lowerCamelCase ), "score": ANY(lowerCamelCase )}] , ) self.assertTrue(outputs[0]["label"] in model.config.idalabel.values() )
81
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _snake_case : int = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : List[Any] , **lowerCamelCase : int ) -> None: warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
def lowerCAmelCase_ ( __lowerCamelCase ): stooge(__lowerCamelCase , 0 , len(__lowerCamelCase ) - 1 ) return arr def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if i >= h: return # If first element is smaller than the last then swap them if arr[i] > arr[h]: __snake_case , __snake_case : Any = arr[h], arr[i] # If there are more than 2 elements in the array if h - i + 1 > 2: __snake_case : List[str] = (int)((h - i + 1) / 3 ) # Recursively sort first 2/3 elements stooge(__lowerCamelCase , __lowerCamelCase , (h - t) ) # Recursively sort last 2/3 elements stooge(__lowerCamelCase , i + t , (__lowerCamelCase) ) # Recursively sort first 2/3 elements stooge(__lowerCamelCase , __lowerCamelCase , (h - t) ) if __name__ == "__main__": _snake_case : List[Any] = input("Enter numbers separated by a comma:\n").strip() _snake_case : str = [int(item) for item in user_input.split(",")] print(stooge_sort(unsorted))
81
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 _snake_case : Optional[Any] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[str] = ["pixel_values"] def __init__( self : List[Any] , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : int = 8 , **lowerCamelCase : Tuple , ) -> None: super().__init__(**lowerCamelCase ) __snake_case : Dict = do_rescale __snake_case : Dict = rescale_factor __snake_case : Optional[Any] = do_pad __snake_case : Tuple = pad_size def __snake_case ( self : Dict , lowerCamelCase : np.ndarray , lowerCamelCase : float , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Optional[int] ) -> np.ndarray: return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : int , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None ) -> Tuple: __snake_case , __snake_case : List[str] = get_image_size(lowerCamelCase ) __snake_case : Optional[Any] = (old_height // size + 1) * size - old_height __snake_case : List[Any] = (old_width // size + 1) * size - old_width return pad(lowerCamelCase , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCamelCase ) def __snake_case ( self : Tuple , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : Union[str, Any] , ) -> List[str]: __snake_case : int = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : str = do_pad if do_pad is not None else self.do_pad __snake_case : Any = pad_size if pad_size is not None else self.pad_size __snake_case : int = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __snake_case : str = [to_numpy_array(lowerCamelCase ) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_pad: __snake_case : Optional[Any] = [self.pad(lowerCamelCase , size=lowerCamelCase ) for image in images] __snake_case : int = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __snake_case : Union[str, Any] = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
81
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case : Union[str, Any] = { "configuration_bridgetower": [ "BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP", "BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig", ], "processing_bridgetower": ["BridgeTowerProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["BridgeTowerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[str] = [ "BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST", "BridgeTowerForContrastiveLearning", "BridgeTowerForImageAndTextRetrieval", "BridgeTowerForMaskedLM", "BridgeTowerModel", "BridgeTowerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_bridgetower import ( BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP, BridgeTowerConfig, BridgeTowerTextConfig, BridgeTowerVisionConfig, ) from .processing_bridgetower import BridgeTowerProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_bridgetower import BridgeTowerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bridgetower import ( BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST, BridgeTowerForContrastiveLearning, BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerModel, BridgeTowerPreTrainedModel, ) else: import sys _snake_case : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure)
81
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Any = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, 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 ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class a : """simple docstring""" def __init__( self : int , lowerCamelCase : Optional[int] , lowerCamelCase : int=13 , lowerCamelCase : Tuple=7 , lowerCamelCase : Optional[int]=True , lowerCamelCase : int=True , lowerCamelCase : Any=True , lowerCamelCase : int=True , lowerCamelCase : Optional[int]=99 , lowerCamelCase : Any=64 , lowerCamelCase : Dict=32 , lowerCamelCase : int=5 , lowerCamelCase : List[str]=4 , lowerCamelCase : Optional[int]=37 , lowerCamelCase : List[str]="gelu" , lowerCamelCase : int=0.1 , lowerCamelCase : Tuple=0.1 , lowerCamelCase : Dict=512 , lowerCamelCase : Tuple=16 , lowerCamelCase : int=2 , lowerCamelCase : Any=0.02 , lowerCamelCase : List[Any]=3 , lowerCamelCase : int=4 , lowerCamelCase : Optional[int]=None , ) -> Union[str, Any]: __snake_case : Tuple = parent __snake_case : Tuple = batch_size __snake_case : List[str] = seq_length __snake_case : int = is_training __snake_case : Dict = use_input_mask __snake_case : Optional[Any] = use_token_type_ids __snake_case : int = use_labels __snake_case : int = vocab_size __snake_case : List[str] = hidden_size __snake_case : str = embedding_size __snake_case : Union[str, Any] = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : int = intermediate_size __snake_case : List[str] = hidden_act __snake_case : int = hidden_dropout_prob __snake_case : Dict = attention_probs_dropout_prob __snake_case : Dict = max_position_embeddings __snake_case : Any = type_vocab_size __snake_case : Tuple = type_sequence_label_size __snake_case : Optional[int] = initializer_range __snake_case : Optional[Any] = num_labels __snake_case : List[Any] = num_choices __snake_case : Optional[int] = scope def __snake_case ( self : List[str] ) -> int: __snake_case : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __snake_case : List[str] = None if self.use_input_mask: __snake_case : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) __snake_case : str = None if self.use_token_type_ids: __snake_case : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __snake_case : Tuple = None __snake_case : int = None __snake_case : List[str] = None if self.use_labels: __snake_case : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __snake_case : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __snake_case : List[str] = ids_tensor([self.batch_size] , self.num_choices ) __snake_case : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __snake_case ( self : Any ) -> int: return MegatronBertConfig( 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 , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , ) def __snake_case ( self : Optional[int] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int] , lowerCamelCase : List[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : Any ) -> List[str]: __snake_case : str = MegatronBertModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase ) __snake_case : Tuple = model(lowerCamelCase , token_type_ids=lowerCamelCase ) __snake_case : Optional[int] = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __snake_case ( self : Optional[int] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : int , lowerCamelCase : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : List[Any] ) -> List[Any]: __snake_case : Union[str, Any] = MegatronBertForMaskedLM(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Optional[int] = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __snake_case ( self : Dict , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : int , lowerCamelCase : str , lowerCamelCase : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[Any] ) -> Union[str, Any]: __snake_case : List[str] = MegatronBertForCausalLM(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Tuple = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __snake_case ( self : Optional[Any] , lowerCamelCase : Any , lowerCamelCase : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : int , lowerCamelCase : Dict ) -> Optional[Any]: __snake_case : str = MegatronBertForNextSentencePrediction(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __snake_case ( self : Dict , lowerCamelCase : Optional[int] , lowerCamelCase : Tuple , lowerCamelCase : Dict , lowerCamelCase : List[Any] , lowerCamelCase : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Union[str, Any] ) -> str: __snake_case : str = MegatronBertForPreTraining(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , next_sentence_label=lowerCamelCase , ) 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 __snake_case ( self : Optional[Any] , lowerCamelCase : Tuple , lowerCamelCase : str , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : Dict , lowerCamelCase : List[str] , lowerCamelCase : Union[str, Any] ) -> Tuple: __snake_case : str = MegatronBertForQuestionAnswering(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Dict = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , start_positions=lowerCamelCase , end_positions=lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : int , lowerCamelCase : List[str] , lowerCamelCase : Optional[int] , lowerCamelCase : Tuple , lowerCamelCase : Union[str, Any] , lowerCamelCase : Optional[int] ) -> Tuple: __snake_case : Optional[int] = self.num_labels __snake_case : Union[str, Any] = MegatronBertForSequenceClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Union[str, Any] = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Any , lowerCamelCase : Any , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Union[str, Any]: __snake_case : Tuple = self.num_labels __snake_case : Tuple = MegatronBertForTokenClassification(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[str] = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[str] , lowerCamelCase : List[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Any , lowerCamelCase : Optional[Any] ) -> Dict: __snake_case : List[str] = self.num_choices __snake_case : Dict = MegatronBertForMultipleChoice(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __snake_case : Dict = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __snake_case ( self : Dict ) -> Tuple: __snake_case : Union[str, Any] = self.prepare_config_and_inputs() ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : int = config_and_inputs __snake_case : Optional[Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __UpperCAmelCase : Optional[Any] = ( { "feature-extraction": MegatronBertModel, "fill-mask": MegatronBertForMaskedLM, "question-answering": MegatronBertForQuestionAnswering, "text-classification": MegatronBertForSequenceClassification, "text-generation": MegatronBertForCausalLM, "token-classification": MegatronBertForTokenClassification, "zero-shot": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = True # test_resize_embeddings = False __UpperCAmelCase : Union[str, Any] = False def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : List[str]=False ) -> Any: __snake_case : Tuple = super()._prepare_for_class(lowerCamelCase , lowerCamelCase , return_labels=lowerCamelCase ) if return_labels: if model_class in get_values(lowerCamelCase ): __snake_case : str = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowerCamelCase ) __snake_case : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCamelCase ) return inputs_dict def __snake_case ( self : List[str] ) -> int: __snake_case : Any = MegatronBertModelTester(self ) __snake_case : Union[str, Any] = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 ) def __snake_case ( self : str ) -> str: self.config_tester.run_common_tests() def __snake_case ( self : List[str] ) -> Optional[Any]: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Optional[Any]: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*lowerCamelCase ) def __snake_case ( self : str ) -> List[Any]: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Any: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*lowerCamelCase ) def __snake_case ( self : int ) -> List[Any]: __snake_case : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): return torch.tensor( __lowerCamelCase , dtype=torch.long , device=__lowerCamelCase , ) _snake_case : Optional[Any] = 1E-4 @require_torch @require_sentencepiece @require_tokenizers class a (unittest.TestCase ): """simple docstring""" @slow @unittest.skip("Model is not available." ) def __snake_case ( self : List[Any] ) -> Dict: __snake_case : List[str] = "nvidia/megatron-bert-uncased-345m" if "MYDIR" in os.environ: __snake_case : str = os.path.join(os.environ["MYDIR"] , lowerCamelCase ) __snake_case : Dict = MegatronBertModel.from_pretrained(lowerCamelCase ) model.to(lowerCamelCase ) model.half() __snake_case : int = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase )[0] __snake_case : str = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , lowerCamelCase ) __snake_case : Any = [-0.60_40, -0.25_17, -0.10_25, 0.34_20, -0.67_58, -0.00_17, -0.10_89, -0.19_90, 0.57_28] for ii in range(3 ): for jj in range(3 ): __snake_case : List[Any] = output[0, ii, jj] __snake_case : Tuple = expected[3 * ii + jj] __snake_case : List[str] = "ii={} jj={} a={} b={}".format(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertTrue(math.isclose(lowerCamelCase , lowerCamelCase , rel_tol=lowerCamelCase , abs_tol=lowerCamelCase ) , msg=lowerCamelCase )
81
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging _snake_case : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : CLIPSegForImageSegmentation , lowerCamelCase : CLIPSegProcessor , lowerCamelCase : AutoencoderKL , lowerCamelCase : CLIPTextModel , lowerCamelCase : CLIPTokenizer , lowerCamelCase : UNetaDConditionModel , lowerCamelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCamelCase : StableDiffusionSafetyChecker , lowerCamelCase : CLIPImageProcessor , ) -> Tuple: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __snake_case : Tuple = ( F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : Any = dict(scheduler.config ) __snake_case : List[Any] = 1 __snake_case : Tuple = FrozenDict(lowerCamelCase ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __snake_case : List[str] = ( F'The configuration file of this scheduler: {scheduler} has not set the configuration' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : List[str] = dict(scheduler.config ) __snake_case : List[str] = True __snake_case : Any = FrozenDict(lowerCamelCase ) if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=lowerCamelCase , segmentation_processor=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , ) def __snake_case ( self : Dict , lowerCamelCase : Optional[Union[str, int]] = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Any: self.enable_attention_slicing(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> str: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __snake_case : Optional[int] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase , lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : int ) -> Any: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any] , lowerCamelCase : Union[str, List[str]] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : str , lowerCamelCase : int = 512 , lowerCamelCase : int = 512 , lowerCamelCase : int = 50 , lowerCamelCase : float = 7.5 , lowerCamelCase : Optional[Union[str, List[str]]] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : float = 0.0 , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : Optional[torch.FloatTensor] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase : int = 1 , **lowerCamelCase : Dict , ) -> List[str]: __snake_case : Tuple = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __snake_case : str = self.segmentation_model(**lowerCamelCase ) __snake_case : Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __snake_case : List[Any] = self.numpy_to_pil(lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __snake_case : Tuple = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=lowerCamelCase , image=lowerCamelCase , mask_image=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , )
81
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING _snake_case : List[str] = logging.get_logger(__name__) _snake_case : str = { "SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json", # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : str = "deformable_detr" __UpperCAmelCase : List[str] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : Optional[int] , lowerCamelCase : int=True , lowerCamelCase : Dict=None , lowerCamelCase : Optional[Any]=3 , lowerCamelCase : str=300 , lowerCamelCase : Tuple=1024 , lowerCamelCase : Dict=6 , lowerCamelCase : Any=1024 , lowerCamelCase : List[Any]=8 , lowerCamelCase : Any=6 , lowerCamelCase : Dict=1024 , lowerCamelCase : Dict=8 , lowerCamelCase : Optional[Any]=0.0 , lowerCamelCase : List[str]=True , lowerCamelCase : List[str]="relu" , lowerCamelCase : Optional[Any]=256 , lowerCamelCase : Tuple=0.1 , lowerCamelCase : List[Any]=0.0 , lowerCamelCase : Dict=0.0 , lowerCamelCase : List[str]=0.02 , lowerCamelCase : Optional[Any]=1.0 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Any=False , lowerCamelCase : int="sine" , lowerCamelCase : Union[str, Any]="resnet50" , lowerCamelCase : int=True , lowerCamelCase : List[str]=False , lowerCamelCase : int=4 , lowerCamelCase : str=4 , lowerCamelCase : List[str]=4 , lowerCamelCase : Any=False , lowerCamelCase : Any=300 , lowerCamelCase : Dict=False , lowerCamelCase : List[Any]=1 , lowerCamelCase : Optional[int]=5 , lowerCamelCase : Any=2 , lowerCamelCase : Union[str, Any]=1 , lowerCamelCase : Optional[int]=1 , lowerCamelCase : Optional[Any]=5 , lowerCamelCase : List[str]=2 , lowerCamelCase : int=0.1 , lowerCamelCase : List[str]=0.25 , lowerCamelCase : Optional[int]=False , **lowerCamelCase : int , ) -> Dict: if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) __snake_case : Optional[Any] = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(lowerCamelCase , lowerCamelCase ): __snake_case : Optional[Any] = backbone_config.get("model_type" ) __snake_case : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] __snake_case : str = config_class.from_dict(lowerCamelCase ) __snake_case : Union[str, Any] = use_timm_backbone __snake_case : List[str] = backbone_config __snake_case : Optional[int] = num_channels __snake_case : List[Any] = num_queries __snake_case : Tuple = max_position_embeddings __snake_case : Tuple = d_model __snake_case : List[str] = encoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Tuple = encoder_attention_heads __snake_case : Dict = decoder_ffn_dim __snake_case : int = decoder_layers __snake_case : Optional[int] = decoder_attention_heads __snake_case : Any = dropout __snake_case : List[Any] = attention_dropout __snake_case : List[str] = activation_dropout __snake_case : str = activation_function __snake_case : Optional[int] = init_std __snake_case : Any = init_xavier_std __snake_case : Optional[Any] = encoder_layerdrop __snake_case : Union[str, Any] = auxiliary_loss __snake_case : List[Any] = position_embedding_type __snake_case : List[str] = backbone __snake_case : Tuple = use_pretrained_backbone __snake_case : Dict = dilation # deformable attributes __snake_case : Any = num_feature_levels __snake_case : List[Any] = encoder_n_points __snake_case : List[Any] = decoder_n_points __snake_case : int = two_stage __snake_case : Any = two_stage_num_proposals __snake_case : List[Any] = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError("If two_stage is True, with_box_refine must be True." ) # Hungarian matcher __snake_case : str = class_cost __snake_case : Union[str, Any] = bbox_cost __snake_case : str = giou_cost # Loss coefficients __snake_case : int = mask_loss_coefficient __snake_case : List[str] = dice_loss_coefficient __snake_case : Any = bbox_loss_coefficient __snake_case : List[Any] = giou_loss_coefficient __snake_case : Optional[Any] = eos_coefficient __snake_case : Optional[Any] = focal_alpha __snake_case : int = disable_custom_kernels super().__init__(is_encoder_decoder=lowerCamelCase , **lowerCamelCase ) @property def __snake_case ( self : Optional[int] ) -> int: return self.encoder_attention_heads @property def __snake_case ( self : Dict ) -> int: return self.d_model def __snake_case ( self : Tuple ) -> Optional[int]: __snake_case : Union[str, Any] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __snake_case : Union[str, Any] = self.backbone_config.to_dict() __snake_case : Optional[Any] = self.__class__.model_type return output
81
class a : """simple docstring""" def __init__( self : Tuple , lowerCamelCase : list ) -> None: __snake_case : str = set_counts __snake_case : Union[str, Any] = max(lowerCamelCase ) __snake_case : List[Any] = len(lowerCamelCase ) __snake_case : Tuple = [1] * num_sets __snake_case : Dict = list(range(lowerCamelCase ) ) def __snake_case ( self : str , lowerCamelCase : int , lowerCamelCase : int ) -> bool: __snake_case : List[Any] = self.get_parent(lowerCamelCase ) __snake_case : Tuple = self.get_parent(lowerCamelCase ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] __snake_case : List[str] = 0 __snake_case : List[Any] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __snake_case : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __snake_case : Union[str, Any] = 0 __snake_case : Optional[int] = src_parent __snake_case : Tuple = self.set_counts[src_parent] __snake_case : str = max(self.max_set , lowerCamelCase ) return True def __snake_case ( self : int , lowerCamelCase : int ) -> int: if self.parents[disj_set] == disj_set: return disj_set __snake_case : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
81
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer _snake_case : List[str] = logging.get_logger(__name__) _snake_case : Dict = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} _snake_case : Any = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } _snake_case : str = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } _snake_case : Dict = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Dict = VOCAB_FILES_NAMES __UpperCAmelCase : int = PRETRAINED_VOCAB_FILES_MAP __UpperCAmelCase : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCAmelCase : Optional[Any] = PRETRAINED_INIT_CONFIGURATION __UpperCAmelCase : int = ["input_ids", "attention_mask"] __UpperCAmelCase : Tuple = DistilBertTokenizer def __init__( self : int , lowerCamelCase : Any=None , lowerCamelCase : int=None , lowerCamelCase : Tuple=True , lowerCamelCase : int="[UNK]" , lowerCamelCase : int="[SEP]" , lowerCamelCase : Optional[Any]="[PAD]" , lowerCamelCase : List[str]="[CLS]" , lowerCamelCase : List[Any]="[MASK]" , lowerCamelCase : Dict=True , lowerCamelCase : str=None , **lowerCamelCase : int , ) -> List[Any]: super().__init__( lowerCamelCase , tokenizer_file=lowerCamelCase , do_lower_case=lowerCamelCase , unk_token=lowerCamelCase , sep_token=lowerCamelCase , pad_token=lowerCamelCase , cls_token=lowerCamelCase , mask_token=lowerCamelCase , tokenize_chinese_chars=lowerCamelCase , strip_accents=lowerCamelCase , **lowerCamelCase , ) __snake_case : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCamelCase ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCamelCase ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCamelCase ) != tokenize_chinese_chars ): __snake_case : List[Any] = getattr(lowerCamelCase , normalizer_state.pop("type" ) ) __snake_case : Union[str, Any] = do_lower_case __snake_case : Union[str, Any] = strip_accents __snake_case : List[str] = tokenize_chinese_chars __snake_case : Optional[Any] = normalizer_class(**lowerCamelCase ) __snake_case : List[Any] = do_lower_case def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any=None ) -> Any: __snake_case : Tuple = [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 __snake_case ( self : List[Any] , lowerCamelCase : List[int] , lowerCamelCase : Optional[List[int]] = None ) -> List[int]: __snake_case : Union[str, Any] = [self.sep_token_id] __snake_case : int = [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 __snake_case ( self : str , lowerCamelCase : str , lowerCamelCase : Optional[str] = None ) -> Tuple[str]: __snake_case : str = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase )
81
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : int , lowerCamelCase : Any , lowerCamelCase : int=7 , lowerCamelCase : str=3 , lowerCamelCase : Optional[int]=30 , lowerCamelCase : Dict=400 , lowerCamelCase : str=True , lowerCamelCase : str=None , lowerCamelCase : Any=True , lowerCamelCase : Union[str, Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[int]=1 / 255 , lowerCamelCase : Any=True , ) -> str: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __snake_case : Optional[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __snake_case : Optional[Any] = parent __snake_case : List[Any] = batch_size __snake_case : Optional[int] = num_channels __snake_case : str = min_resolution __snake_case : int = max_resolution __snake_case : int = do_resize __snake_case : Tuple = size __snake_case : Any = do_normalize __snake_case : int = image_mean __snake_case : Tuple = image_std __snake_case : Dict = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : str = do_pad def __snake_case ( self : Any ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __snake_case ( self : Dict , lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any]=False ) -> List[str]: if not batched: __snake_case : Dict = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : Dict = image.size else: __snake_case , __snake_case : List[str] = image.shape[1], image.shape[2] if w < h: __snake_case : Optional[int] = int(self.size["shortest_edge"] * h / w ) __snake_case : int = self.size["shortest_edge"] elif w > h: __snake_case : List[str] = self.size["shortest_edge"] __snake_case : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: __snake_case : List[Any] = self.size["shortest_edge"] __snake_case : Any = self.size["shortest_edge"] else: __snake_case : int = [] for image in image_inputs: __snake_case , __snake_case : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Optional[Any] = ConditionalDetrImageProcessingTester(self ) @property def __snake_case ( self : Any ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any] ) -> Optional[int]: __snake_case : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def __snake_case ( self : Any ) -> Dict: __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) __snake_case : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> Dict: pass def __snake_case ( self : Tuple ) -> str: # Initialize image_processing __snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __snake_case : Dict = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> str: # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : List[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> List[str]: # Initialize image_processing __snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : List[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : int = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __snake_case ( self : Any ) -> Optional[int]: # prepare image and target __snake_case : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : List[Any] = {"image_id": 39769, "annotations": target} # encode them __snake_case : List[str] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __snake_case : List[str] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Optional[int] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : List[Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Optional[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __snake_case : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Tuple = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> Tuple: # prepare image, target and masks_path __snake_case : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : str = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} __snake_case : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __snake_case : int = ConditionalDetrImageProcessor(format="coco_panoptic" ) __snake_case : str = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : Any = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : int = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __snake_case : List[Any] = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __snake_case : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
81
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _snake_case : Any = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Dict = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[str] = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Optional[Any] = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Union[str, Any] = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _snake_case : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _snake_case : Optional[Any] = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _snake_case : Dict = "UperNetConfig" class a (nn.Module ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : Union[int, Tuple[int, int]] , lowerCamelCase : Union[int, Tuple[int, int], str] = 0 , lowerCamelCase : bool = False , lowerCamelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() __snake_case : Union[str, Any] = nn.Convad( in_channels=lowerCamelCase , out_channels=lowerCamelCase , kernel_size=lowerCamelCase , padding=lowerCamelCase , bias=lowerCamelCase , dilation=lowerCamelCase , ) __snake_case : Dict = nn.BatchNormad(lowerCamelCase ) __snake_case : List[Any] = nn.ReLU() def __snake_case ( self : List[Any] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : Dict = self.conv(lowerCamelCase ) __snake_case : int = self.batch_norm(lowerCamelCase ) __snake_case : Optional[Any] = self.activation(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : str , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ) -> None: super().__init__() __snake_case : Tuple = [ nn.AdaptiveAvgPoolad(lowerCamelCase ), UperNetConvModule(lowerCamelCase , lowerCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : Dict , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : List[str] = input for layer in self.layers: __snake_case : Tuple = layer(lowerCamelCase ) return hidden_state class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple[int, ...] , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : bool ) -> None: super().__init__() __snake_case : Dict = pool_scales __snake_case : List[str] = align_corners __snake_case : List[Any] = in_channels __snake_case : str = channels __snake_case : Optional[Any] = [] for i, pool_scale in enumerate(lowerCamelCase ): __snake_case : Union[str, Any] = UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase , in_channels=lowerCamelCase , channels=lowerCamelCase ) self.blocks.append(lowerCamelCase ) self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> List[torch.Tensor]: __snake_case : Tuple = [] for ppm in self.blocks: __snake_case : Any = ppm(lowerCamelCase ) __snake_case : List[Any] = nn.functional.interpolate( lowerCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(lowerCamelCase ) return ppm_outs class a (nn.Module ): """simple docstring""" def __init__( self : int , lowerCamelCase : str , lowerCamelCase : str ) -> List[str]: super().__init__() __snake_case : Dict = config __snake_case : List[str] = config.pool_scales # e.g. (1, 2, 3, 6) __snake_case : Tuple = in_channels __snake_case : str = config.hidden_size __snake_case : List[str] = False __snake_case : Any = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __snake_case : Tuple = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __snake_case : List[str] = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __snake_case : List[Any] = nn.ModuleList() __snake_case : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __snake_case : Union[str, Any] = UperNetConvModule(lowerCamelCase , self.channels , kernel_size=1 ) __snake_case : Optional[int] = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(lowerCamelCase ) self.fpn_convs.append(lowerCamelCase ) __snake_case : int = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def __snake_case ( self : List[str] ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> str: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : List[Any] , lowerCamelCase : Tuple ) -> Optional[int]: __snake_case : str = inputs[-1] __snake_case : int = [x] psp_outs.extend(self.psp_modules(lowerCamelCase ) ) __snake_case : Tuple = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Union[str, Any] = self.bottleneck(lowerCamelCase ) return output def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # build laterals __snake_case : Any = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(lowerCamelCase ) ) # build top-down path __snake_case : Dict = len(lowerCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Union[str, Any] = laterals[i - 1].shape[2:] __snake_case : Optional[int] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=lowerCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs __snake_case : str = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Tuple = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) __snake_case : str = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Optional[Any] = self.fpn_bottleneck(lowerCamelCase ) __snake_case : Tuple = self.classifier(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int = 2 , lowerCamelCase : int = 3 , lowerCamelCase : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() __snake_case : List[Any] = config __snake_case : List[str] = config.auxiliary_in_channels __snake_case : List[Any] = config.auxiliary_channels __snake_case : Tuple = config.auxiliary_num_convs __snake_case : int = config.auxiliary_concat_input __snake_case : Optional[int] = in_index __snake_case : Tuple = (kernel_size // 2) * dilation __snake_case : Optional[int] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) if self.num_convs == 0: __snake_case : Union[str, Any] = nn.Identity() else: __snake_case : Any = nn.Sequential(*lowerCamelCase ) if self.concat_input: __snake_case : int = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=lowerCamelCase , padding=kernel_size // 2 ) __snake_case : Optional[Any] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def __snake_case ( self : Dict ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : Tuple ) -> Optional[int]: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : Optional[int] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps __snake_case : List[str] = encoder_hidden_states[self.in_index] __snake_case : Optional[Any] = self.convs(lowerCamelCase ) if self.concat_input: __snake_case : Optional[Any] = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __snake_case : Union[str, Any] = self.classifier(lowerCamelCase ) return output class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = UperNetConfig __UpperCAmelCase : int = "pixel_values" __UpperCAmelCase : str = True def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> List[Any]: if isinstance(lowerCamelCase , lowerCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def __snake_case ( self : Optional[Any] ) -> List[str]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def __snake_case ( self : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[Any]=False ) -> Dict: if isinstance(lowerCamelCase , lowerCamelCase ): __snake_case : Union[str, Any] = value _snake_case : Dict = R"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _snake_case : Tuple = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , _lowerCAmelCase , ) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Dict , lowerCamelCase : int ) -> Optional[int]: super().__init__(lowerCamelCase ) __snake_case : Any = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __snake_case : Union[str, Any] = UperNetHead(lowerCamelCase , in_channels=self.backbone.channels ) __snake_case : Any = UperNetFCNHead(lowerCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: __snake_case : Any = return_dict if return_dict is not None else self.config.use_return_dict __snake_case : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case : str = output_attentions if output_attentions is not None else self.config.output_attentions __snake_case : Tuple = self.backbone.forward_with_filtered_kwargs( lowerCamelCase , output_hidden_states=lowerCamelCase , output_attentions=lowerCamelCase ) __snake_case : List[Any] = outputs.feature_maps __snake_case : List[Any] = self.decode_head(lowerCamelCase ) __snake_case : List[str] = nn.functional.interpolate(lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : Optional[int] = None if self.auxiliary_head is not None: __snake_case : Dict = self.auxiliary_head(lowerCamelCase ) __snake_case : Dict = nn.functional.interpolate( lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : int = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss __snake_case : Any = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __snake_case : Union[str, Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __snake_case : Any = (logits,) + outputs[1:] else: __snake_case : str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
81
1
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : Optional[Any] , lowerCamelCase : List[str]=7 , lowerCamelCase : Union[str, Any]=3 , lowerCamelCase : Dict=30 , lowerCamelCase : Any=400 , lowerCamelCase : List[str]=True , lowerCamelCase : Union[str, Any]=None , lowerCamelCase : Tuple=True , lowerCamelCase : int=1 / 255 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=[0.5, 0.5, 0.5] , lowerCamelCase : int=[0.5, 0.5, 0.5] , lowerCamelCase : Union[str, Any]=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __snake_case : str = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __snake_case : Union[str, Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Union[str, Any] = num_channels __snake_case : Dict = min_resolution __snake_case : Optional[Any] = max_resolution __snake_case : Tuple = do_resize __snake_case : Tuple = size __snake_case : Optional[int] = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : Optional[Any] = do_normalize __snake_case : Union[str, Any] = image_mean __snake_case : Any = image_std __snake_case : str = do_pad def __snake_case ( self : Any ) -> Union[str, Any]: return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : List[str]=False ) -> Any: if not batched: __snake_case : List[Any] = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : Union[str, Any] = image.size else: __snake_case , __snake_case : Dict = image.shape[1], image.shape[2] if w < h: __snake_case : Optional[int] = int(self.size["shortest_edge"] * h / w ) __snake_case : Optional[int] = self.size["shortest_edge"] elif w > h: __snake_case : List[Any] = self.size["shortest_edge"] __snake_case : str = int(self.size["shortest_edge"] * w / h ) else: __snake_case : Any = self.size["shortest_edge"] __snake_case : Any = self.size["shortest_edge"] else: __snake_case : Tuple = [] for image in image_inputs: __snake_case , __snake_case : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : List[str] = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : Optional[int] = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = DetrImageProcessor if is_vision_available() else None def __snake_case ( self : Optional[int] ) -> Tuple: __snake_case : int = DetrImageProcessingTester(self ) @property def __snake_case ( self : Union[str, Any] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any] ) -> List[str]: __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "rescale_factor" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) def __snake_case ( self : List[str] ) -> Optional[int]: __snake_case : Tuple = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) __snake_case : Optional[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def __snake_case ( self : Any ) -> Optional[Any]: pass def __snake_case ( self : str ) -> int: # Initialize image_processing __snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Any = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case , __snake_case : Any = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __snake_case : List[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : List[Any] ) -> int: # Initialize image_processing __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Dict = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Tuple = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Dict = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : Tuple ) -> str: # Initialize image_processing __snake_case : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : str = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Tuple = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : int = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __snake_case ( self : Dict ) -> str: # prepare image and target __snake_case : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __snake_case : List[str] = json.loads(f.read() ) __snake_case : Union[str, Any] = {"image_id": 39769, "annotations": target} # encode them __snake_case : str = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50" ) __snake_case : Optional[int] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : int = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : str = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : str = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Union[str, Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : List[Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __snake_case : str = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : List[str] = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def __snake_case ( self : Tuple ) -> Union[str, Any]: # prepare image, target and masks_path __snake_case : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __snake_case : List[str] = json.loads(f.read() ) __snake_case : Union[str, Any] = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} __snake_case : Tuple = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __snake_case : Dict = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50-panoptic" ) __snake_case : List[Any] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : List[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : List[str] = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Any = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : str = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Any = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : Any = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __snake_case : str = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __snake_case : Tuple = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
81
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase ): if not nums: return 0 __snake_case : Any = nums[0] __snake_case : str = 0 for num in nums[1:]: __snake_case , __snake_case : List[str] = ( max_excluding + num, max(__lowerCamelCase , __lowerCamelCase ), ) return max(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
from __future__ import annotations _snake_case : Optional[Any] = 8.9_88E9 # units = N * m^s * C^-2 def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Dict = abs(chargea * chargea ) if (force, chargea, chargea, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if distance < 0: raise ValueError("Distance cannot be negative" ) if force == 0: __snake_case : str = COULOMBS_CONSTANT * charge_product / (distance**2) return {"force": force} elif chargea == 0: __snake_case : List[Any] = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge1": chargea} elif chargea == 0: __snake_case : int = abs(__lowerCamelCase ) * (distance**2) / (COULOMBS_CONSTANT * chargea) return {"charge2": chargea} elif distance == 0: __snake_case : List[Any] = (COULOMBS_CONSTANT * charge_product / abs(__lowerCamelCase )) ** 0.5 return {"distance": distance} raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
81
from __future__ import annotations from typing import Any def lowerCAmelCase_ ( __lowerCamelCase ): create_state_space_tree(__lowerCamelCase , [] , 0 ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == len(__lowerCamelCase ): print(__lowerCamelCase ) return create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _snake_case : list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
81
1
import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : bool = True , lowerCamelCase : Dict[str, int] = None , lowerCamelCase : int = 32 , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : bool = True , lowerCamelCase : Optional[Union[float, List[float]]] = [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , lowerCamelCase : Optional[Union[float, List[float]]] = [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , lowerCamelCase : bool = True , lowerCamelCase : Union[str, Any]=7 , lowerCamelCase : int=30 , lowerCamelCase : Union[str, Any]=400 , lowerCamelCase : Union[str, Any]=3 , ) -> Tuple: __snake_case : int = parent __snake_case : Optional[Any] = do_resize __snake_case : List[Any] = size if size is not None else {"shortest_edge": 288} __snake_case : Tuple = size_divisor __snake_case : List[Any] = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : Optional[int] = do_normalize __snake_case : Optional[Any] = do_center_crop __snake_case : List[str] = image_mean __snake_case : Optional[int] = image_std __snake_case : Optional[int] = do_pad __snake_case : Tuple = batch_size __snake_case : Optional[Any] = num_channels __snake_case : Optional[int] = min_resolution __snake_case : Any = max_resolution def __snake_case ( self : List[Any] ) -> Any: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def __snake_case ( self : Optional[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int]=False ) -> str: if not batched: __snake_case : Tuple = self.size["shortest_edge"] __snake_case : Optional[Any] = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : List[Any] = image.size else: __snake_case , __snake_case : Dict = image.shape[1], image.shape[2] __snake_case : Dict = size / min(lowerCamelCase , lowerCamelCase ) if h < w: __snake_case , __snake_case : Union[str, Any] = size, scale * w else: __snake_case , __snake_case : List[Any] = scale * h, size __snake_case : int = int((1333 / 800) * size ) if max(lowerCamelCase , lowerCamelCase ) > max_size: __snake_case : Union[str, Any] = max_size / max(lowerCamelCase , lowerCamelCase ) __snake_case : int = newh * scale __snake_case : Optional[int] = neww * scale __snake_case , __snake_case : Any = int(newh + 0.5 ), int(neww + 0.5 ) __snake_case , __snake_case : int = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: __snake_case : Tuple = [] for image in image_inputs: __snake_case , __snake_case : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : Dict = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = BridgeTowerImageProcessor if is_vision_available() else None def __snake_case ( self : Dict ) -> int: __snake_case : List[Any] = BridgeTowerImageProcessingTester(self ) @property def __snake_case ( self : List[str] ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Any ) -> Any: __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) self.assertTrue(hasattr(lowerCamelCase , "size_divisor" ) ) def __snake_case ( self : List[str] ) -> List[Any]: pass def __snake_case ( self : List[str] ) -> Dict: # Initialize image processor __snake_case : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : int = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Optional[int] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Any = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : List[Any] ) -> List[Any]: # Initialize image processor __snake_case : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Tuple = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Optional[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Tuple = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : str ) -> Tuple: # Initialize image processor __snake_case : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : Union[str, Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
81
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
1
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : int = (num_of_terms / 2) * (2 * first_term + (num_of_terms - 1) * common_diff) # formula for sum of series return total def lowerCAmelCase_ ( ): print(sum_of_series(1 , 1 , 1_0 ) ) if __name__ == "__main__": import doctest doctest.testmod()
81
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 a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).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() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).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() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = 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 __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = 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": __snake_case : Union[str, Any] = 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": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
1
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy _snake_case : str = logging.getLogger(__name__) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = False , ): __snake_case : Union[str, Any] = bnb_quantization_config.load_in_abit __snake_case : List[str] = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," " make sure you have the latest version of `bitsandbytes` installed." ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," "make sure you have the latest version of `bitsandbytes` installed." ) __snake_case : Tuple = [] # custom device map if isinstance(__lowerCamelCase , __lowerCamelCase ) and len(device_map.keys() ) > 1: __snake_case : int = [key for key, value in device_map.items() if value in ["disk", "cpu"]] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: __snake_case : str = get_keys_to_not_convert(__lowerCamelCase ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(__lowerCamelCase ) __snake_case : int = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: __snake_case : Union[str, Any] = [] __snake_case : Any = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(__lowerCamelCase ) # compatibility with peft __snake_case : int = load_in_abit __snake_case : Union[str, Any] = load_in_abit __snake_case : Union[str, Any] = get_parameter_device(__lowerCamelCase ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( "It is not recommended to quantize a loaded model. " "The model should be instantiated under the `init_empty_weights` context manager." ) __snake_case : Optional[int] = replace_with_bnb_layers(__lowerCamelCase , __lowerCamelCase , modules_to_not_convert=__lowerCamelCase ) # convert param to the right dtype __snake_case : Any = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: __snake_case : Optional[int] = name.replace(".weight" , "" ).replace(".bias" , "" ) __snake_case : Dict = getattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(__lowerCamelCase ): param.to(__lowerCamelCase ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info( F'The model device type is {model_device.type}. However, cuda is needed for quantization.' "We move the model to cuda." ) return model elif weights_location is None: raise RuntimeError( F'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' ) else: with init_empty_weights(): __snake_case : List[Any] = replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , modules_to_not_convert=__lowerCamelCase ) __snake_case : Any = get_quantized_model_device_map( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , max_memory=__lowerCamelCase , no_split_module_classes=__lowerCamelCase , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): __snake_case : str = True __snake_case : int = any(x in list(device_map.values() ) for x in ["cpu", "disk"] ) load_checkpoint_in_model( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , dtype=bnb_quantization_config.torch_dtype , offload_folder=__lowerCamelCase , offload_state_dict=__lowerCamelCase , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(__lowerCamelCase , device_map=__lowerCamelCase , offload_dir=__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=None ): if device_map is None: if torch.cuda.is_available(): __snake_case : Dict = {"": torch.cuda.current_device()} else: raise RuntimeError("No GPU found. A GPU is needed for quantization." ) logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`." ) if isinstance(__lowerCamelCase , __lowerCamelCase ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " "'sequential'." ) __snake_case : Union[str, Any] = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) __snake_case : Any = {} __snake_case : Tuple = special_dtypes __snake_case : Dict = no_split_module_classes __snake_case : Union[str, Any] = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": __snake_case : Optional[int] = get_balanced_memory( __lowerCamelCase , low_zero=(device_map == "balanced_low_0") , max_memory=__lowerCamelCase , **__lowerCamelCase , ) __snake_case : Optional[Any] = max_memory __snake_case : Tuple = infer_auto_device_map(__lowerCamelCase , **__lowerCamelCase ) if isinstance(__lowerCamelCase , __lowerCamelCase ): # check if don't have any quantized module on the cpu __snake_case : str = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules __snake_case : int = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( "\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n " ) else: logger.info( "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" ) del device_map_without_some_modules return device_map def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None ): if modules_to_not_convert is None: __snake_case : Any = [] __snake_case , __snake_case : Union[str, Any] = _replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) if not has_been_replaced: logger.warning( "You are loading your model in 8bit or 4bit but no linear modules were found in your model." " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." " Please double check your model architecture, or submit an issue on github if you think this is" " a bug." ) return model def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , ): __snake_case : List[str] = False for name, module in model.named_children(): if current_key_name is None: __snake_case : List[Any] = [] current_key_name.append(__lowerCamelCase ) if isinstance(__lowerCamelCase , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` __snake_case : Optional[int] = ".".join(__lowerCamelCase ) __snake_case : List[str] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: __snake_case : Union[str, Any] = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: __snake_case : Dict = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=__lowerCamelCase , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: __snake_case : Optional[int] = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError("load_in_8bit and load_in_4bit can't be both False" ) __snake_case : Dict = module.weight.data if module.bias is not None: __snake_case : Any = module.bias.data bnb_module.requires_grad_(__lowerCamelCase ) setattr(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) __snake_case : Optional[Any] = True if len(list(module.children() ) ) > 0: __snake_case , __snake_case : Optional[Any] = _replace_with_bnb_layers( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) __snake_case : Optional[Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase_ ( __lowerCamelCase ): # Create a copy of the model with init_empty_weights(): __snake_case : List[str] = deepcopy(__lowerCamelCase ) # this has 0 cost since it is done inside `init_empty_weights` context manager` __snake_case : Tuple = find_tied_parameters(__lowerCamelCase ) # For compatibility with Accelerate < 0.18 if isinstance(__lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: __snake_case : Optional[int] = sum(__lowerCamelCase , [] ) __snake_case : Union[str, Any] = len(__lowerCamelCase ) > 0 # Check if it is a base model __snake_case : int = False if hasattr(__lowerCamelCase , "base_model_prefix" ): __snake_case : Dict = not hasattr(__lowerCamelCase , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head __snake_case : Dict = list(model.named_children() ) __snake_case : List[Any] = [list_modules[-1][0]] # add last module together with tied weights __snake_case : Dict = set(__lowerCamelCase ) - set(__lowerCamelCase ) __snake_case : Union[str, Any] = list(set(__lowerCamelCase ) ) + list(__lowerCamelCase ) # remove ".weight" from the keys __snake_case : Optional[int] = [".weight", ".bias"] __snake_case : Dict = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: __snake_case : int = name.replace(__lowerCamelCase , "" ) filtered_module_names.append(__lowerCamelCase ) return filtered_module_names def lowerCAmelCase_ ( __lowerCamelCase ): for m in model.modules(): if isinstance(__lowerCamelCase , bnb.nn.Linearabit ): return True return False def lowerCAmelCase_ ( __lowerCamelCase ): return next(parameter.parameters() ).device def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(__lowerCamelCase , __lowerCamelCase , 0 , dtype=__lowerCamelCase , value=__lowerCamelCase ) __snake_case : Tuple = param_name __snake_case : Union[str, Any] = model if "." in tensor_name: __snake_case : Any = tensor_name.split("." ) for split in splits[:-1]: __snake_case : int = getattr(__lowerCamelCase , __lowerCamelCase ) if new_module is None: raise ValueError(F'{module} has no attribute {split}.' ) __snake_case : str = new_module __snake_case : List[str] = splits[-1] # offload weights __snake_case : int = False offload_weight(module._parameters[tensor_name] , __lowerCamelCase , __lowerCamelCase , index=__lowerCamelCase ) if hasattr(module._parameters[tensor_name] , "SCB" ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace("weight" , "SCB" ) , __lowerCamelCase , index=__lowerCamelCase , ) else: offload_weight(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , index=__lowerCamelCase ) offload_weight(__lowerCamelCase , param_name.replace("weight" , "SCB" ) , __lowerCamelCase , index=__lowerCamelCase ) set_module_tensor_to_device(__lowerCamelCase , __lowerCamelCase , "meta" , dtype=__lowerCamelCase , value=torch.empty(*param.size() ) )
81
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _snake_case : Optional[int] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[Any] , *lowerCamelCase : Any , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
import argparse import os import torch from transformers import ( XLNetConfig, XLNetForQuestionAnswering, XLNetForSequenceClassification, XLNetLMHeadModel, load_tf_weights_in_xlnet, ) from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging _snake_case : int = { "cola": 2, "mnli": 3, "mrpc": 2, "sst-2": 2, "sts-b": 1, "qqp": 2, "qnli": 2, "rte": 2, "wnli": 2, } logging.set_verbosity_info() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None ): # Initialise PyTorch model __snake_case : Any = XLNetConfig.from_json_file(__lowerCamelCase ) __snake_case : Optional[int] = finetuning_task.lower() if finetuning_task is not None else "" if finetuning_task in GLUE_TASKS_NUM_LABELS: print(F'Building PyTorch XLNetForSequenceClassification model from configuration: {config}' ) __snake_case : List[Any] = finetuning_task __snake_case : Any = GLUE_TASKS_NUM_LABELS[finetuning_task] __snake_case : int = XLNetForSequenceClassification(__lowerCamelCase ) elif "squad" in finetuning_task: __snake_case : Optional[Any] = finetuning_task __snake_case : Dict = XLNetForQuestionAnswering(__lowerCamelCase ) else: __snake_case : Tuple = XLNetLMHeadModel(__lowerCamelCase ) # Load weights from tf checkpoint load_tf_weights_in_xlnet(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # Save pytorch-model __snake_case : List[Any] = os.path.join(__lowerCamelCase , __lowerCamelCase ) __snake_case : Optional[Any] = os.path.join(__lowerCamelCase , __lowerCamelCase ) print(F'Save PyTorch model to {os.path.abspath(__lowerCamelCase )}' ) torch.save(model.state_dict() , __lowerCamelCase ) print(F'Save configuration file to {os.path.abspath(__lowerCamelCase )}' ) with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": _snake_case : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path." ) parser.add_argument( "--xlnet_config_file", default=None, type=str, required=True, help=( "The config json file corresponding to the pre-trained XLNet model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--finetuning_task", default=None, type=str, help="Name of a task on which the XLNet TensorFlow model was fine-tuned", ) _snake_case : Optional[int] = parser.parse_args() print(args) convert_xlnet_checkpoint_to_pytorch( args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task )
81
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Any = SamImageProcessor() __snake_case : Optional[int] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Optional[int] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : int ) -> List[Any]: __snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[Any] ) -> Dict: __snake_case : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : List[str] ) -> Tuple: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Optional[int] = self.prepare_image_inputs() __snake_case : List[str] = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : Dict = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Tuple = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[str] = [torch.ones((1, 3, 5, 5) )] __snake_case : Tuple = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : int = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , torch.tensor(lowerCamelCase ) , torch.tensor(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : List[str] = [np.ones((1, 3, 5, 5) )] __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : str = [[1, 0], [0, 1]] with self.assertRaises(lowerCamelCase ): __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) @require_vision @require_tf class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : int = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : str , **lowerCamelCase : Any ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : Dict = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : int ) -> List[str]: __snake_case : List[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: __snake_case : str = self.get_image_processor() __snake_case : Union[str, Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : int = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : List[str] = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def __snake_case ( self : Any ) -> Optional[int]: __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Union[str, Any] = [tf.ones((1, 3, 5, 5) )] __snake_case : List[Any] = [[1764, 2646]] __snake_case : Dict = [[683, 1024]] __snake_case : List[str] = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , tf.convert_to_tensor(lowerCamelCase ) , tf.convert_to_tensor(lowerCamelCase ) , return_tensors="tf" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : Union[str, Any] = [np.ones((1, 3, 5, 5) )] __snake_case : List[str] = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Tuple = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __snake_case : Dict = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[str] , **lowerCamelCase : Any ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : str = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __snake_case : Dict = [tf.convert_to_tensor(lowerCamelCase )] __snake_case : List[Any] = [torch.tensor(lowerCamelCase )] __snake_case : Optional[Any] = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : Union[str, Any] = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) __snake_case : Dict = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : Any = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : Any = image_processor(lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Optional[Any] = processor(images=lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Tuple = image_processor(lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() __snake_case : List[Any] = processor(images=lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) )
81
1
import argparse import os from . import ( ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, BART_PRETRAINED_MODEL_ARCHIVE_LIST, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, BartConfig, BertConfig, CamembertConfig, CTRLConfig, DistilBertConfig, DPRConfig, ElectraConfig, FlaubertConfig, GPTaConfig, LayoutLMConfig, LxmertConfig, OpenAIGPTConfig, RobertaConfig, TaConfig, TFAlbertForPreTraining, TFBartForConditionalGeneration, TFBartForSequenceClassification, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFCamembertForMaskedLM, TFCTRLLMHeadModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, TFElectraForPreTraining, TFFlaubertWithLMHeadModel, TFGPTaLMHeadModel, TFLayoutLMForMaskedLM, TFLxmertForPreTraining, TFLxmertVisualFeatureEncoder, TFOpenAIGPTLMHeadModel, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForSequenceClassification, TFTaForConditionalGeneration, TFTransfoXLLMHeadModel, TFWavaVecaModel, TFXLMRobertaForMaskedLM, TFXLMWithLMHeadModel, TFXLNetLMHeadModel, TransfoXLConfig, WavaVecaConfig, WavaVecaModel, XLMConfig, XLMRobertaConfig, XLNetConfig, is_torch_available, load_pytorch_checkpoint_in_tfa_model, ) from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging if is_torch_available(): import numpy as np import torch from . import ( AlbertForPreTraining, BartForConditionalGeneration, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, CamembertForMaskedLM, CTRLLMHeadModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, DPRContextEncoder, DPRQuestionEncoder, DPRReader, ElectraForPreTraining, FlaubertWithLMHeadModel, GPTaLMHeadModel, LayoutLMForMaskedLM, LxmertForPreTraining, LxmertVisualFeatureEncoder, OpenAIGPTLMHeadModel, RobertaForMaskedLM, RobertaForSequenceClassification, TaForConditionalGeneration, TransfoXLLMHeadModel, XLMRobertaForMaskedLM, XLMWithLMHeadModel, XLNetLMHeadModel, ) logging.set_verbosity_info() _snake_case : Dict = { "bart": ( BartConfig, TFBartForConditionalGeneration, TFBartForSequenceClassification, BartForConditionalGeneration, BART_PRETRAINED_MODEL_ARCHIVE_LIST, ), "bert": ( BertConfig, TFBertForPreTraining, BertForPreTraining, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-uncased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-large-cased-whole-word-masking-finetuned-squad": ( BertConfig, TFBertForQuestionAnswering, BertForQuestionAnswering, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "bert-base-cased-finetuned-mrpc": ( BertConfig, TFBertForSequenceClassification, BertForSequenceClassification, BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "dpr": ( DPRConfig, TFDPRQuestionEncoder, TFDPRContextEncoder, TFDPRReader, DPRQuestionEncoder, DPRContextEncoder, DPRReader, DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, ), "gpt2": ( GPTaConfig, TFGPTaLMHeadModel, GPTaLMHeadModel, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlnet": ( XLNetConfig, TFXLNetLMHeadModel, XLNetLMHeadModel, XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm": ( XLMConfig, TFXLMWithLMHeadModel, XLMWithLMHeadModel, XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "xlm-roberta": ( XLMRobertaConfig, TFXLMRobertaForMaskedLM, XLMRobertaForMaskedLM, XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "transfo-xl": ( TransfoXLConfig, TFTransfoXLLMHeadModel, TransfoXLLMHeadModel, TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "openai-gpt": ( OpenAIGPTConfig, TFOpenAIGPTLMHeadModel, OpenAIGPTLMHeadModel, OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "roberta": ( RobertaConfig, TFRobertaForCausalLM, TFRobertaForMaskedLM, RobertaForMaskedLM, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "layoutlm": ( LayoutLMConfig, TFLayoutLMForMaskedLM, LayoutLMForMaskedLM, LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, ), "roberta-large-mnli": ( RobertaConfig, TFRobertaForSequenceClassification, RobertaForSequenceClassification, ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "camembert": ( CamembertConfig, TFCamembertForMaskedLM, CamembertForMaskedLM, CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "flaubert": ( FlaubertConfig, TFFlaubertWithLMHeadModel, FlaubertWithLMHeadModel, FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert": ( DistilBertConfig, TFDistilBertForMaskedLM, DistilBertForMaskedLM, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "distilbert-base-distilled-squad": ( DistilBertConfig, TFDistilBertForQuestionAnswering, DistilBertForQuestionAnswering, DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert": ( LxmertConfig, TFLxmertForPreTraining, LxmertForPreTraining, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "lxmert-visual-feature-encoder": ( LxmertConfig, TFLxmertVisualFeatureEncoder, LxmertVisualFeatureEncoder, LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "ctrl": ( CTRLConfig, TFCTRLLMHeadModel, CTRLLMHeadModel, CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "albert": ( AlbertConfig, TFAlbertForPreTraining, AlbertForPreTraining, ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "t5": ( TaConfig, TFTaForConditionalGeneration, TaForConditionalGeneration, T5_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "electra": ( ElectraConfig, TFElectraForPreTraining, ElectraForPreTraining, ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP, ), "wav2vec2": ( WavaVecaConfig, TFWavaVecaModel, WavaVecaModel, WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP, ), } def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=False , __lowerCamelCase=True ): if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type, should be one of {list(MODEL_CLASSES.keys() )}.' ) __snake_case , __snake_case , __snake_case , __snake_case : Optional[Any] = MODEL_CLASSES[model_type] # Initialise TF model if config_file in aws_config_map: __snake_case : List[Any] = cached_file(__lowerCamelCase , __lowerCamelCase , force_download=not use_cached_models ) __snake_case : Tuple = config_class.from_json_file(__lowerCamelCase ) __snake_case : Optional[int] = True __snake_case : Optional[int] = True print(F'Building TensorFlow model from configuration: {config}' ) __snake_case : str = model_class(__lowerCamelCase ) # Load weights from tf checkpoint if pytorch_checkpoint_path in aws_config_map.keys(): __snake_case : str = cached_file( __lowerCamelCase , __lowerCamelCase , force_download=not use_cached_models ) # Load PyTorch checkpoint in tf2 model: __snake_case : int = load_pytorch_checkpoint_in_tfa_model(__lowerCamelCase , __lowerCamelCase ) if compare_with_pt_model: __snake_case : Any = tf_model(tf_model.dummy_inputs , training=__lowerCamelCase ) # build the network __snake_case : Tuple = torch.load(__lowerCamelCase , map_location="cpu" ) __snake_case : Tuple = pt_model_class.from_pretrained( pretrained_model_name_or_path=__lowerCamelCase , config=__lowerCamelCase , state_dict=__lowerCamelCase ) with torch.no_grad(): __snake_case : List[Any] = pt_model(**pt_model.dummy_inputs ) __snake_case : Optional[int] = pto[0].numpy() __snake_case : Union[str, Any] = tfo[0].numpy() __snake_case : Dict = np.amax(np.abs(np_pt - np_tf ) ) print(F'Max absolute difference between models outputs {diff}' ) assert diff <= 2e-2, F'Error, model absolute difference is >2e-2: {diff}' # Save pytorch-model print(F'Save TensorFlow model to {tf_dump_path}' ) tf_model.save_weights(__lowerCamelCase , save_format="h5" ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=None , __lowerCamelCase=None , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , __lowerCamelCase=False , ): if args_model_type is None: __snake_case : Any = list(MODEL_CLASSES.keys() ) else: __snake_case : Optional[int] = [args_model_type] for j, model_type in enumerate(__lowerCamelCase , start=1 ): print("=" * 1_0_0 ) print(F' Converting model type {j}/{len(__lowerCamelCase )}: {model_type}' ) print("=" * 1_0_0 ) if model_type not in MODEL_CLASSES: raise ValueError(F'Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys() )}.' ) __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : Any = MODEL_CLASSES[model_type] if model_shortcut_names_or_path is None: __snake_case : Optional[int] = list(aws_model_maps.keys() ) if config_shortcut_names_or_path is None: __snake_case : List[str] = model_shortcut_names_or_path for i, (model_shortcut_name, config_shortcut_name) in enumerate( zip(__lowerCamelCase , __lowerCamelCase ) , start=1 ): print("-" * 1_0_0 ) if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name: if not only_convert_finetuned_models: print(F' Skipping finetuned checkpoint {model_shortcut_name}' ) continue __snake_case : Dict = model_shortcut_name elif only_convert_finetuned_models: print(F' Skipping not finetuned checkpoint {model_shortcut_name}' ) continue print( F' Converting checkpoint {i}/{len(__lowerCamelCase )}: {model_shortcut_name} - model_type {model_type}' ) print("-" * 1_0_0 ) if config_shortcut_name in aws_config_map: __snake_case : List[str] = cached_file(__lowerCamelCase , __lowerCamelCase , force_download=not use_cached_models ) else: __snake_case : List[Any] = config_shortcut_name if model_shortcut_name in aws_model_maps: __snake_case : str = cached_file(__lowerCamelCase , __lowerCamelCase , force_download=not use_cached_models ) else: __snake_case : str = model_shortcut_name if os.path.isfile(__lowerCamelCase ): __snake_case : List[Any] = "converted_model" convert_pt_checkpoint_to_tf( model_type=__lowerCamelCase , pytorch_checkpoint_path=__lowerCamelCase , config_file=__lowerCamelCase , tf_dump_path=os.path.join(__lowerCamelCase , model_shortcut_name + "-tf_model.h5" ) , compare_with_pt_model=__lowerCamelCase , ) if remove_cached_files: os.remove(__lowerCamelCase ) os.remove(__lowerCamelCase ) if __name__ == "__main__": _snake_case : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--tf_dump_path", default=None, type=str, required=True, help="Path to the output Tensorflow dump file." ) parser.add_argument( "--model_type", default=None, type=str, help=( f'''Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and ''' "convert all the models from AWS." ), ) parser.add_argument( "--pytorch_checkpoint_path", default=None, type=str, help=( "Path to the PyTorch checkpoint path or shortcut name to download from AWS. " "If not given, will download and convert all the checkpoints from AWS." ), ) parser.add_argument( "--config_file", default=None, type=str, help=( "The config json file corresponding to the pre-trained model. \n" "This specifies the model architecture. If not given and " "--pytorch_checkpoint_path is not given or is a shortcut name " "use the configuration associated to the shortcut name on the AWS" ), ) parser.add_argument( "--compare_with_pt_model", action="store_true", help="Compare Tensorflow and PyTorch model predictions." ) parser.add_argument( "--use_cached_models", action="store_true", help="Use cached models if possible instead of updating to latest checkpoint versions.", ) parser.add_argument( "--remove_cached_files", action="store_true", help="Remove pytorch models after conversion (save memory when converting in batches).", ) parser.add_argument("--only_convert_finetuned_models", action="store_true", help="Only convert finetuned models.") _snake_case : str = parser.parse_args() # if args.pytorch_checkpoint_path is not None: # convert_pt_checkpoint_to_tf(args.model_type.lower(), # args.pytorch_checkpoint_path, # args.config_file if args.config_file is not None else args.pytorch_checkpoint_path, # args.tf_dump_path, # compare_with_pt_model=args.compare_with_pt_model, # use_cached_models=args.use_cached_models) # else: convert_all_pt_checkpoints_to_tf( args.model_type.lower() if args.model_type is not None else None, args.tf_dump_path, model_shortcut_names_or_path=[args.pytorch_checkpoint_path] if args.pytorch_checkpoint_path is not None else None, config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None, compare_with_pt_model=args.compare_with_pt_model, use_cached_models=args.use_cached_models, remove_cached_files=args.remove_cached_files, only_convert_finetuned_models=args.only_convert_finetuned_models, )
81
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowerCamelCase : str , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def lowerCAmelCase_ ( __lowerCamelCase ): return x + 2 class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Any: __snake_case : Optional[Any] = "x = 3" __snake_case : Any = {} __snake_case : Optional[int] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) assert result == 3 self.assertDictEqual(lowerCamelCase , {"x": 3} ) __snake_case : str = "x = y" __snake_case : List[Any] = {"y": 5} __snake_case : Any = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 5, "y": 5} ) def __snake_case ( self : Any ) -> List[str]: __snake_case : int = "y = add_two(x)" __snake_case : Any = {"x": 3} __snake_case : str = evaluate(lowerCamelCase , {"add_two": add_two} , state=lowerCamelCase ) assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 3, "y": 5} ) # Won't work without the tool with CaptureStdout() as out: __snake_case : str = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) assert result is None assert "tried to execute add_two" in out.out def __snake_case ( self : Dict ) -> str: __snake_case : str = "x = 3" __snake_case : List[Any] = {} __snake_case : List[Any] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) assert result == 3 self.assertDictEqual(lowerCamelCase , {"x": 3} ) def __snake_case ( self : Optional[int] ) -> List[Any]: __snake_case : Union[str, Any] = "test_dict = {'x': x, 'y': add_two(x)}" __snake_case : Tuple = {"x": 3} __snake_case : List[Any] = evaluate(lowerCamelCase , {"add_two": add_two} , state=lowerCamelCase ) self.assertDictEqual(lowerCamelCase , {"x": 3, "y": 5} ) self.assertDictEqual(lowerCamelCase , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __snake_case ( self : Optional[int] ) -> int: __snake_case : int = "x = 3\ny = 5" __snake_case : Optional[int] = {} __snake_case : List[str] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 3, "y": 5} ) def __snake_case ( self : Dict ) -> Tuple: __snake_case : List[Any] = "text = f'This is x: {x}.'" __snake_case : List[Any] = {"x": 3} __snake_case : List[str] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(lowerCamelCase , {"x": 3, "text": "This is x: 3."} ) def __snake_case ( self : Any ) -> Dict: __snake_case : List[str] = "if x <= 3:\n y = 2\nelse:\n y = 5" __snake_case : Tuple = {"x": 3} __snake_case : int = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(lowerCamelCase , {"x": 3, "y": 2} ) __snake_case : str = {"x": 8} __snake_case : List[str] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 8, "y": 5} ) def __snake_case ( self : int ) -> int: __snake_case : Tuple = "test_list = [x, add_two(x)]" __snake_case : List[str] = {"x": 3} __snake_case : Any = evaluate(lowerCamelCase , {"add_two": add_two} , state=lowerCamelCase ) self.assertListEqual(lowerCamelCase , [3, 5] ) self.assertDictEqual(lowerCamelCase , {"x": 3, "test_list": [3, 5]} ) def __snake_case ( self : Union[str, Any] ) -> Union[str, Any]: __snake_case : Optional[int] = "y = x" __snake_case : Any = {"x": 3} __snake_case : Union[str, Any] = evaluate(lowerCamelCase , {} , state=lowerCamelCase ) assert result == 3 self.assertDictEqual(lowerCamelCase , {"x": 3, "y": 3} ) def __snake_case ( self : Any ) -> Any: __snake_case : Optional[Any] = "test_list = [x, add_two(x)]\ntest_list[1]" __snake_case : str = {"x": 3} __snake_case : Optional[int] = evaluate(lowerCamelCase , {"add_two": add_two} , state=lowerCamelCase ) assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 3, "test_list": [3, 5]} ) __snake_case : str = "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']" __snake_case : Optional[Any] = {"x": 3} __snake_case : Union[str, Any] = evaluate(lowerCamelCase , {"add_two": add_two} , state=lowerCamelCase ) assert result == 5 self.assertDictEqual(lowerCamelCase , {"x": 3, "test_dict": {"x": 3, "y": 5}} ) def __snake_case ( self : Dict ) -> List[Any]: __snake_case : Any = "x = 0\nfor i in range(3):\n x = i" __snake_case : Union[str, Any] = {} __snake_case : Any = evaluate(lowerCamelCase , {"range": range} , state=lowerCamelCase ) assert result == 2 self.assertDictEqual(lowerCamelCase , {"x": 2, "i": 2} )
81
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case : Union[str, Any] = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["OwlViTFeatureExtractor"] _snake_case : Optional[int] = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _snake_case : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer _snake_case : Union[str, Any] = ["bert-base-uncased", "bert-base-cased"] _snake_case : Dict = "hf-internal-testing/tiny-bert-tf-only" if is_tf_available(): class a (tf.keras.Model ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : List[Any] ) -> Dict: super().__init__() __snake_case : List[Any] = tokenizer __snake_case : Dict = AutoConfig.from_pretrained(lowerCamelCase ) __snake_case : Dict = TFAutoModel.from_config(lowerCamelCase ) def __snake_case ( self : Optional[int] , lowerCamelCase : Optional[Any] ) -> Optional[int]: __snake_case : int = self.tokenizer(lowerCamelCase ) __snake_case : Dict = self.bert(**lowerCamelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Union[str, Any] ) -> Optional[Any]: super().setUp() __snake_case : str = [ BertTokenizer.from_pretrained(lowerCamelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false __snake_case : str = [TFBertTokenizer.from_pretrained(lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(lowerCamelCase , use_fast_bert_tokenizer=lowerCamelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __snake_case : Optional[int] = [ "This is a straightforward English test sentence.", "This one has some weird characters\rto\nsee\r\nif those\u00E9break things.", "Now we're going to add some Chinese: 一 二 三 一二三", "And some much more rare Chinese: 齉 堃 齉堃", "Je vais aussi écrire en français pour tester les accents", "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ", ] __snake_case : Tuple = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __snake_case ( self : Tuple ) -> str: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): __snake_case : Optional[Any] = tokenizer(lowerCamelCase , return_tensors="tf" , padding="longest" ) __snake_case : int = tf_tokenizer(lowerCamelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def __snake_case ( self : Any ) -> Dict: for tf_tokenizer in self.tf_tokenizers: __snake_case : List[Any] = tf_tokenizer(self.paired_sentences ) __snake_case : List[Any] = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def __snake_case ( self : Dict ) -> Optional[int]: for tf_tokenizer in self.tf_tokenizers: __snake_case : Optional[int] = tf.function(lowerCamelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): __snake_case : Tuple = tf.constant(lowerCamelCase ) __snake_case : int = compiled_tokenizer(lowerCamelCase ) __snake_case : str = tf_tokenizer(lowerCamelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __snake_case ( self : Union[str, Any] ) -> str: for tf_tokenizer in self.tf_tokenizers: __snake_case : Optional[int] = ModelToSave(tokenizer=lowerCamelCase ) __snake_case : Any = tf.convert_to_tensor(self.test_sentences ) __snake_case : Any = model(lowerCamelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __snake_case : Optional[Any] = Path(lowerCamelCase ) / "saved.model" model.save(lowerCamelCase ) __snake_case : Tuple = tf.keras.models.load_model(lowerCamelCase ) __snake_case : Optional[Any] = loaded_model(lowerCamelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1E-5 )
81
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : str = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "van" def __init__( self : Optional[int] , lowerCamelCase : Any=224 , lowerCamelCase : str=3 , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : Dict=[4, 2, 2, 2] , lowerCamelCase : List[Any]=[64, 128, 320, 512] , lowerCamelCase : str=[3, 3, 12, 3] , lowerCamelCase : Dict=[8, 8, 4, 4] , lowerCamelCase : Any="gelu" , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Tuple=1E-6 , lowerCamelCase : Optional[int]=1E-2 , lowerCamelCase : int=0.0 , lowerCamelCase : Optional[Any]=0.0 , **lowerCamelCase : Optional[int] , ) -> int: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = image_size __snake_case : Any = num_channels __snake_case : Any = patch_sizes __snake_case : List[Any] = strides __snake_case : str = hidden_sizes __snake_case : Dict = depths __snake_case : Optional[int] = mlp_ratios __snake_case : Dict = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : Optional[int] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : int = dropout_rate
81
1
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = F'{sampling_rate}' __snake_case : List[Any] = "1" __snake_case : List[Any] = "f32le" __snake_case : Any = [ "ffmpeg", "-i", "pipe:0", "-ac", ac, "-ar", ar, "-f", format_for_conversion, "-hide_banner", "-loglevel", "quiet", "pipe:1", ] try: with subprocess.Popen(__lowerCamelCase , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: __snake_case : Any = ffmpeg_process.communicate(__lowerCamelCase ) except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to load audio files from filename" ) from error __snake_case : str = output_stream[0] __snake_case : List[str] = np.frombuffer(__lowerCamelCase , np.floataa ) if audio.shape[0] == 0: raise ValueError("Malformed soundfile" ) return audio def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = "f32le" , ): __snake_case : List[Any] = F'{sampling_rate}' __snake_case : List[str] = "1" if format_for_conversion == "s16le": __snake_case : Optional[int] = 2 elif format_for_conversion == "f32le": __snake_case : str = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) __snake_case : List[str] = platform.system() if system == "Linux": __snake_case : Tuple = "alsa" __snake_case : Union[str, Any] = "default" elif system == "Darwin": __snake_case : str = "avfoundation" __snake_case : Any = ":0" elif system == "Windows": __snake_case : Any = "dshow" __snake_case : Optional[int] = "default" __snake_case : List[str] = [ "ffmpeg", "-f", format_, "-i", input_, "-ac", ac, "-ar", ar, "-f", format_for_conversion, "-fflags", "nobuffer", "-hide_banner", "-loglevel", "quiet", "pipe:1", ] __snake_case : str = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample __snake_case : Tuple = _ffmpeg_stream(__lowerCamelCase , __lowerCamelCase ) for item in iterator: yield item def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None , __lowerCamelCase = "f32le" , ): if stream_chunk_s is not None: __snake_case : str = stream_chunk_s else: __snake_case : Union[str, Any] = chunk_length_s __snake_case : Union[str, Any] = ffmpeg_microphone(__lowerCamelCase , __lowerCamelCase , format_for_conversion=__lowerCamelCase ) if format_for_conversion == "s16le": __snake_case : List[Any] = np.intaa __snake_case : int = 2 elif format_for_conversion == "f32le": __snake_case : List[Any] = np.floataa __snake_case : Optional[int] = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) if stride_length_s is None: __snake_case : Optional[Any] = chunk_length_s / 6 __snake_case : Union[str, Any] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(__lowerCamelCase , (int, float) ): __snake_case : Tuple = [stride_length_s, stride_length_s] __snake_case : List[Any] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample __snake_case : Any = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample __snake_case : Tuple = datetime.datetime.now() __snake_case : Union[str, Any] = datetime.timedelta(seconds=__lowerCamelCase ) for item in chunk_bytes_iter(__lowerCamelCase , __lowerCamelCase , stride=(stride_left, stride_right) , stream=__lowerCamelCase ): # Put everything back in numpy scale __snake_case : Union[str, Any] = np.frombuffer(item["raw"] , dtype=__lowerCamelCase ) __snake_case : List[str] = ( item["stride"][0] // size_of_sample, item["stride"][1] // size_of_sample, ) __snake_case : Optional[Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 1_0 * delta: # We're late !! SKIP continue yield item def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = False ): __snake_case : Optional[Any] = b"" __snake_case , __snake_case : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( F'Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}' ) __snake_case : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(__lowerCamelCase ) < chunk_len: __snake_case : Tuple = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(__lowerCamelCase ) >= chunk_len: # We are flushing the accumulator __snake_case : List[str] = (_stride_left, stride_right) __snake_case : int = {"raw": acc[:chunk_len], "stride": stride} if stream: __snake_case : Any = False yield item __snake_case : Optional[int] = stride_left __snake_case : Dict = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(__lowerCamelCase ) > stride_left: __snake_case : int = {"raw": acc, "stride": (_stride_left, 0)} if stream: __snake_case : Optional[Any] = False yield item def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = 2**2_4 # 16Mo try: with subprocess.Popen(__lowerCamelCase , stdout=subprocess.PIPE , bufsize=__lowerCamelCase ) as ffmpeg_process: while True: __snake_case : Any = ffmpeg_process.stdout.read(__lowerCamelCase ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to stream audio files from filename" ) from error
81
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case : Union[str, Any] = logging.getLogger(__name__) def lowerCAmelCase_ ( ): __snake_case : int = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __snake_case : List[str] = parser.parse_args() return args def lowerCAmelCase_ ( __lowerCamelCase ): def fn(__lowerCamelCase ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = [] for i in range(len(tokenized_data["input_ids"] ) ): __snake_case : Tuple = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase ) __snake_case : str = tf.train.Example(features=__lowerCamelCase ) __snake_case : List[str] = example.SerializeToString() records.append(__lowerCamelCase ) return records def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) __snake_case : Dict = dataset.select(range(__lowerCamelCase ) ) print(F'Limiting the dataset to {args.limit} entries.' ) __snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __snake_case : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: __snake_case : str = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __snake_case : Any = tokenize_function(__lowerCamelCase ) __snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__lowerCamelCase ): # Concatenate all texts. __snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()} __snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __snake_case : int = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result __snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 ) __snake_case : Optional[Any] = 0 __snake_case : Optional[Any] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): __snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size] __snake_case : Any = len(dataset_snapshot["input_ids"] ) __snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' ) __snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): __snake_case : Union[str, Any] = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase ) if __name__ == "__main__": _snake_case : List[Any] = parse_args() main(args)
81
1
def lowerCAmelCase_ ( __lowerCamelCase ): if not nums: # Makes sure that the list is not empty raise ValueError("List is empty" ) __snake_case : str = sum(__lowerCamelCase ) / len(__lowerCamelCase ) # Calculate the average return sum(abs(x - average ) for x in nums ) / len(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
81
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _snake_case : List[Any] = "\\n Text data.\n Second line of data." _snake_case : Tuple = "file" @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") __snake_case : Optional[Any] = bytes(__lowerCamelCase , "utf-8" ) with zstd.open(__lowerCamelCase , "wb" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture def lowerCAmelCase_ ( __lowerCamelCase ): with open(os.path.join(tmpfs.local_root_dir , __lowerCamelCase ) , "w" ) as f: f.write(__lowerCamelCase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} __snake_case : str = input_paths[compression_format] __snake_case : Optional[Any] = tmp_path / "cache" __snake_case : Optional[int] = DownloadConfig(cache_dir=__lowerCamelCase , extract_compressed_file=__lowerCamelCase ) __snake_case : Union[str, Any] = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) with open(__lowerCamelCase ) as f: __snake_case : Dict = f.read() with open(__lowerCamelCase ) as f: __snake_case : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = "custom_cache" __snake_case : List[str] = "custom_extracted_dir" __snake_case : Any = tmp_path / "custom_extracted_path" if default_extracted: __snake_case : List[Any] = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __lowerCamelCase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__lowerCamelCase ) ) __snake_case : Optional[Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __snake_case : Optional[int] = xz_file __snake_case : Optional[int] = ( DownloadConfig(extract_compressed_file=__lowerCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__lowerCamelCase ) ) __snake_case : str = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) assert Path(__lowerCamelCase ).parent.parts[-2:] == expected def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : Optional[Any] = str(Path(__lowerCamelCase ).resolve() ) assert cached_path(__lowerCamelCase ) == text_file # relative path __snake_case : Any = str(Path(__lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(__lowerCamelCase ) == text_file def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) # relative path __snake_case : Optional[int] = "./__missing_file__.txt" with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : str = get_from_cache(F'tmp://{tmpfs_file}' ) with open(__lowerCamelCase ) as f: __snake_case : Union[str, Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( ): with pytest.raises(__lowerCamelCase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): http_get("https://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[str] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): ftp_get("ftp://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): fsspec_get("s3://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): fsspec_head("s3://huggingface.co" )
81
1
import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json _snake_case : Dict = "sshleifer/mar_enro_6_3_student" class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : Dict ) -> Any: super().setUp() __snake_case : str = cached_path( "https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz" , extract_compressed_file=lowerCamelCase , ) __snake_case : Optional[int] = F'{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k' @slow @require_torch_gpu def __snake_case ( self : str ) -> Optional[Any]: MarianMTModel.from_pretrained(lowerCamelCase ) @slow @require_torch_gpu def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : List[Any] = { "$MAX_LEN": 64, "$BS": 64, "$GAS": 1, "$ENRO_DIR": self.data_dir, "facebook/mbart-large-cc25": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", "--learning_rate=3e-5": "--learning_rate 3e-4", "--num_train_epochs 6": "--num_train_epochs 1", } # Clean up bash script __snake_case : Optional[Any] = (self.test_file_dir / "train_mbart_cc25_enro.sh").open().read().split("finetune.py" )[1].strip() __snake_case : Any = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) for k, v in env_vars_to_replace.items(): __snake_case : List[str] = bash_script.replace(lowerCamelCase , str(lowerCamelCase ) ) __snake_case : Any = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") __snake_case : int = F'\n --output_dir {output_dir}\n --tokenizer_name Helsinki-NLP/opus-mt-en-ro\n --sortish_sampler\n --do_predict\n --gpus 1\n --freeze_encoder\n --n_train 40000\n --n_val 500\n --n_test 500\n --fp16_opt_level O1\n --num_sanity_val_steps 0\n --eval_beams 2\n '.split() # XXX: args.gpus > 1 : handle multi_gpu in the future __snake_case : Tuple = ["finetune.py"] + bash_script.split() + args with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __snake_case : Optional[Any] = argparse.ArgumentParser() __snake_case : Tuple = pl.Trainer.add_argparse_args(lowerCamelCase ) __snake_case : List[str] = SummarizationModule.add_model_specific_args(lowerCamelCase , os.getcwd() ) __snake_case : List[Any] = parser.parse_args() __snake_case : Optional[int] = main(lowerCamelCase ) # Check metrics __snake_case : Union[str, Any] = load_json(model.metrics_save_path ) __snake_case : Any = metrics["val"][0] __snake_case : Tuple = metrics["val"][-1] self.assertEqual(len(metrics["val"] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[F'val_avg_{model.val_metric}'] , lowerCamelCase ) self.assertGreater(last_step_stats["val_avg_gen_time"] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["val_avg_gen_time"] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["val_avg_bleu"] - first_step_stats["val_avg_bleu"] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["val_avg_bleu"] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["val"][-1]["val_avg_bleu"] - metrics["test"][-1]["test_avg_bleu"] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict __snake_case : Tuple = os.listdir(lowerCamelCase ) __snake_case : Optional[int] = [x for x in contents if x.endswith(".ckpt" )][0] __snake_case : Dict = os.path.join(args.output_dir , lowerCamelCase ) __snake_case : str = torch.load(lowerCamelCase , map_location="cpu" ) __snake_case : Union[str, Any] = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __snake_case : str = {os.path.basename(lowerCamelCase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1 class a (_lowerCAmelCase ): """simple docstring""" @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __snake_case ( self : Tuple ) -> int: __snake_case : int = F'{self.test_file_dir_str}/test_data/wmt_en_ro' __snake_case : Optional[Any] = { "--fp16_opt_level=O1": "", "$MAX_LEN": 128, "$BS": 16, "$GAS": 1, "$ENRO_DIR": data_dir, "$m": "sshleifer/student_marian_en_ro_6_1", "val_check_interval=0.25": "val_check_interval=1.0", } # Clean up bash script __snake_case : List[Any] = ( (self.test_file_dir / "distil_marian_no_teacher.sh").open().read().split("distillation.py" )[1].strip() ) __snake_case : int = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) __snake_case : List[str] = bash_script.replace("--fp16 " , " " ) for k, v in env_vars_to_replace.items(): __snake_case : int = bash_script.replace(lowerCamelCase , str(lowerCamelCase ) ) __snake_case : Dict = self.get_auto_remove_tmp_dir() __snake_case : int = bash_script.replace("--fp16" , "" ) __snake_case : List[str] = 6 __snake_case : int = ( ["distillation.py"] + bash_script.split() + [ F'--output_dir={output_dir}', "--gpus=1", "--learning_rate=1e-3", F'--num_train_epochs={epochs}', "--warmup_steps=10", "--val_check_interval=1.0", "--do_predict", ] ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __snake_case : Optional[Any] = argparse.ArgumentParser() __snake_case : Any = pl.Trainer.add_argparse_args(lowerCamelCase ) __snake_case : int = SummarizationDistiller.add_model_specific_args(lowerCamelCase , os.getcwd() ) __snake_case : Union[str, Any] = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu __snake_case : Union[str, Any] = distill_main(lowerCamelCase ) # Check metrics __snake_case : Dict = load_json(model.metrics_save_path ) __snake_case : List[Any] = metrics["val"][0] __snake_case : List[str] = metrics["val"][-1] assert len(metrics["val"] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[F'val_avg_{model.val_metric}'] , lowerCamelCase ) # check lightning ckpt can be loaded and has a reasonable statedict __snake_case : List[str] = os.listdir(lowerCamelCase ) __snake_case : int = [x for x in contents if x.endswith(".ckpt" )][0] __snake_case : List[str] = os.path.join(args.output_dir , lowerCamelCase ) __snake_case : Optional[Any] = torch.load(lowerCamelCase , map_location="cpu" ) __snake_case : int = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: __snake_case : Optional[int] = {os.path.basename(lowerCamelCase ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1
81
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = start # add current to visited visited.append(__lowerCamelCase ) __snake_case : List[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __snake_case : Tuple = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # if all neighbors visited add current to sort sort.append(__lowerCamelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCamelCase ) != len(__lowerCamelCase ): for vertice in vertices: if vertice not in visited: __snake_case : int = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # return sort return sort if __name__ == "__main__": _snake_case : List[Any] = topological_sort("a", [], []) print(sort)
81
1
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): print("\nThe shortest path matrix using Floyd Warshall algorithm\n" ) for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): if dist[i][j] != float("inf" ): print(int(dist[i][j] ) , end="\t" ) else: print("INF" , end="\t" ) print() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): __snake_case : int = [[float("inf" ) for _ in range(__lowerCamelCase )] for _ in range(__lowerCamelCase )] for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): __snake_case : Optional[Any] = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(__lowerCamelCase ): # looping through rows of graph array for i in range(__lowerCamelCase ): # looping through columns of graph array for j in range(__lowerCamelCase ): if ( dist[i][k] != float("inf" ) and dist[k][j] != float("inf" ) and dist[i][k] + dist[k][j] < dist[i][j] ): __snake_case : List[Any] = dist[i][k] + dist[k][j] _print_dist(__lowerCamelCase , __lowerCamelCase ) return dist, v if __name__ == "__main__": _snake_case : int = int(input("Enter number of vertices: ")) _snake_case : List[str] = int(input("Enter number of edges: ")) _snake_case : str = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): _snake_case : Dict = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) _snake_case : str = int(input("Enter source:")) _snake_case : Any = int(input("Enter destination:")) _snake_case : Tuple = float(input("Enter weight:")) _snake_case : Union[str, Any] = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
81
def lowerCAmelCase_ ( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(__lowerCamelCase , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
81
1
import unittest from knapsack import knapsack as k class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> Dict: __snake_case : Any = 0 __snake_case : List[str] = [0] __snake_case : List[str] = [0] __snake_case : List[str] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 0 ) __snake_case : str = [60] __snake_case : Union[str, Any] = [10] __snake_case : Optional[int] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 0 ) def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : int = 3 __snake_case : List[str] = [1, 2, 3] __snake_case : Any = [3, 2, 1] __snake_case : Tuple = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 5 ) def __snake_case ( self : Dict ) -> List[str]: __snake_case : Optional[int] = 50 __snake_case : int = [60, 100, 120] __snake_case : Dict = [10, 20, 30] __snake_case : List[str] = len(lowerCamelCase ) self.assertEqual(k.knapsack(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) , 220 ) if __name__ == "__main__": unittest.main()
81
from math import sqrt def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0_0_0 ): __snake_case : int = 0 __snake_case : int = 0 __snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__lowerCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
81
1
import requests _snake_case : Optional[Any] = "YOUR API KEY" def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase = giphy_api_key ): __snake_case : Optional[int] = "+".join(query.split() ) __snake_case : List[Any] = F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' __snake_case : Any = requests.get(__lowerCamelCase ).json()["data"] return [gif["url"] for gif in gifs] if __name__ == "__main__": print("\n".join(get_gifs("space ship")))
81
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : str ) -> str: __snake_case : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "neck_hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) ) class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Tuple=13 , lowerCamelCase : str=32 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=3 , lowerCamelCase : Any=640 , lowerCamelCase : Optional[Any]=4 , lowerCamelCase : Tuple="silu" , lowerCamelCase : int=3 , lowerCamelCase : Dict=32 , lowerCamelCase : str=0.1 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=0.02 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=10 , lowerCamelCase : int=None , ) -> str: __snake_case : Optional[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Any = image_size __snake_case : List[Any] = patch_size __snake_case : Any = num_channels __snake_case : Union[str, Any] = last_hidden_size __snake_case : Any = num_attention_heads __snake_case : Any = hidden_act __snake_case : Tuple = conv_kernel_size __snake_case : Any = output_stride __snake_case : Any = hidden_dropout_prob __snake_case : List[Any] = attention_probs_dropout_prob __snake_case : Optional[Any] = classifier_dropout_prob __snake_case : Union[str, Any] = use_labels __snake_case : Optional[int] = is_training __snake_case : Dict = num_labels __snake_case : Any = initializer_range __snake_case : Optional[int] = scope def __snake_case ( self : str ) -> Union[str, Any]: __snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : List[Any] = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __snake_case : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case ( self : Any ) -> Union[str, Any]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] ) -> Dict: __snake_case : List[Any] = MobileViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[str] = model(lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ) -> List[str]: __snake_case : str = self.num_labels __snake_case : List[Any] = MobileViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Dict: __snake_case : Union[str, Any] = self.num_labels __snake_case : Optional[int] = MobileViTForSemanticSegmentation(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Tuple = model(lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[int] ) -> List[Any]: __snake_case : Optional[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = config_and_inputs __snake_case : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Optional[Any] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Optional[int] = False def __snake_case ( self : Optional[int] ) -> Dict: __snake_case : Tuple = MobileViTModelTester(self ) __snake_case : Any = MobileViTConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds" ) def __snake_case ( self : Dict ) -> Any: pass @unittest.skip(reason="MobileViT does not support input and output embeddings" ) def __snake_case ( self : Dict ) -> List[Any]: pass @unittest.skip(reason="MobileViT does not output attentions" ) def __snake_case ( self : int ) -> Dict: pass def __snake_case ( self : int ) -> Union[str, Any]: __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = model_class(lowerCamelCase ) __snake_case : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __snake_case ( self : int ) -> Tuple: pass def __snake_case ( self : Any ) -> Tuple: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : Any ) -> str: def check_hidden_states_output(lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any ): __snake_case : int = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __snake_case : int = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __snake_case : Union[str, Any] = outputs.hidden_states __snake_case : int = 5 self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __snake_case : List[Any] = 2 for i in range(len(lowerCamelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __snake_case , __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : List[Any] = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Any ) -> Any: __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> List[str]: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase ) @slow def __snake_case ( self : List[str] ) -> Any: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = MobileViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def lowerCAmelCase_ ( ): __snake_case : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a (unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : str ) -> Dict: return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None @slow def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : Tuple = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowerCamelCase ) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Dict = model(**lowerCamelCase ) # verify the logits __snake_case : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : str ) -> Optional[int]: __snake_case : Optional[int] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : str = model.to(lowerCamelCase ) __snake_case : int = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Optional[int] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : List[str] = model(**lowerCamelCase ) __snake_case : Union[str, Any] = outputs.logits # verify the logits __snake_case : Tuple = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , lowerCamelCase ) __snake_case : Union[str, Any] = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ] , device=lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : Union[str, Any] ) -> Optional[int]: __snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Tuple = model.to(lowerCamelCase ) __snake_case : Dict = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Any = model(**lowerCamelCase ) __snake_case : Dict = outputs.logits.detach().cpu() __snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(50, 60)] ) __snake_case : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , lowerCamelCase ) __snake_case : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ) __snake_case : Optional[int] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , lowerCamelCase )
81
1
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging _snake_case : List[str] = logging.get_logger(__name__) def lowerCAmelCase_ ( __lowerCamelCase ): if isinstance(__lowerCamelCase , np.ndarray ): return list(tensor.shape ) __snake_case : Optional[Any] = tf.shape(__lowerCamelCase ) if tensor.shape == tf.TensorShape(__lowerCamelCase ): return dynamic __snake_case : Optional[int] = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(__lowerCamelCase )] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase = None , __lowerCamelCase = None ): return tf.nn.softmax(logits=logits + 1e-9 , axis=__lowerCamelCase , name=__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase=1e-5 , __lowerCamelCase=-1 ): # This is a very simplified functional layernorm, designed to duplicate # the functionality of PyTorch nn.functional.layer_norm when this is needed to port # models in Transformers. if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__lowerCamelCase , __lowerCamelCase ): raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis." ) # Get mean and variance on the axis to be normalized __snake_case , __snake_case : int = tf.nn.moments(__lowerCamelCase , axes=[axis] , keepdims=__lowerCamelCase ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis __snake_case : Optional[int] = [1] * inputs.shape.rank __snake_case : Union[str, Any] = shape_list(__lowerCamelCase )[axis] __snake_case : Any = tf.reshape(__lowerCamelCase , __lowerCamelCase ) __snake_case : Any = tf.reshape(__lowerCamelCase , __lowerCamelCase ) # Compute layer normalization using the batch_normalization # function. __snake_case : Dict = tf.nn.batch_normalization( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , offset=__lowerCamelCase , scale=__lowerCamelCase , variance_epsilon=__lowerCamelCase , ) return outputs def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase=0 , __lowerCamelCase=-1 ): # Replicates the behavior of torch.flatten in TF # If end_dim or start_dim is negative, count them from the end if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input __snake_case : Any = tf.shape(__lowerCamelCase ) __snake_case : Any = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) __snake_case : Union[str, Any] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(__lowerCamelCase , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): if not isinstance(__lowerCamelCase , tf.Tensor ): __snake_case : Dict = tf.convert_to_tensor(__lowerCamelCase ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: __snake_case : List[str] = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: __snake_case : Any = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) __snake_case : Dict = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = "input_ids" ): tf.debugging.assert_less( __lowerCamelCase , tf.cast(__lowerCamelCase , dtype=tensor.dtype ) , message=( F'The maximum value of {tensor_name} ({tf.math.reduce_max(__lowerCamelCase )}) must be smaller than the embedding ' F'layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.' ) , ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : int = 6_4_5_1_2 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. __snake_case : Dict = [x for x in data if len(__lowerCamelCase ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( "The following attributes cannot be saved to HDF5 file because " F'they are larger than {HDF5_OBJECT_HEADER_LIMIT} ' F'bytes: {bad_attributes}' ) __snake_case : Optional[int] = np.asarray(__lowerCamelCase ) __snake_case : Any = 1 __snake_case : List[Any] = np.array_split(__lowerCamelCase , __lowerCamelCase ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 __snake_case : str = np.array_split(__lowerCamelCase , __lowerCamelCase ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(__lowerCamelCase ): __snake_case : Any = chunk_data else: __snake_case : Optional[Any] = data def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): if name in group.attrs: __snake_case : Optional[int] = [n.decode("utf8" ) if hasattr(__lowerCamelCase , "decode" ) else n for n in group.attrs[name]] else: __snake_case : int = [] __snake_case : Union[str, Any] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode("utf8" ) if hasattr(__lowerCamelCase , "decode" ) else n for n in group.attrs["%s%d" % (name, chunk_id)]] ) chunk_id += 1 return data def lowerCAmelCase_ ( __lowerCamelCase ): def _expand_single_ad_tensor(__lowerCamelCase ): if isinstance(__lowerCamelCase , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(__lowerCamelCase , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , __lowerCamelCase )
81
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _snake_case : int = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : List[Any] , **lowerCamelCase : int ) -> None: warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class a (_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" @register_to_config def __init__( self : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : float , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : str , lowerCamelCase : bool = False , ) -> Any: super().__init__() __snake_case : str = nn.Embedding(lowerCamelCase , lowerCamelCase ) __snake_case : Tuple = nn.Embedding(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = False __snake_case : int = nn.Dropout(p=lowerCamelCase ) __snake_case : int = TaConfig( vocab_size=lowerCamelCase , d_model=lowerCamelCase , num_heads=lowerCamelCase , d_kv=lowerCamelCase , d_ff=lowerCamelCase , dropout_rate=lowerCamelCase , feed_forward_proj=lowerCamelCase , is_decoder=lowerCamelCase , is_encoder_decoder=lowerCamelCase , ) __snake_case : Tuple = nn.ModuleList() for lyr_num in range(lowerCamelCase ): __snake_case : int = TaBlock(lowerCamelCase ) self.encoders.append(lowerCamelCase ) __snake_case : Union[str, Any] = TaLayerNorm(lowerCamelCase ) __snake_case : List[str] = nn.Dropout(p=lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : int , lowerCamelCase : List[str] ) -> List[Any]: __snake_case : Dict = self.token_embedder(lowerCamelCase ) __snake_case : Optional[int] = encoder_input_tokens.shape[1] __snake_case : Optional[int] = torch.arange(lowerCamelCase , device=encoder_input_tokens.device ) x += self.position_encoding(lowerCamelCase ) __snake_case : Any = self.dropout_pre(lowerCamelCase ) # inverted the attention mask __snake_case : int = encoder_input_tokens.size() __snake_case : int = self.get_extended_attention_mask(lowerCamelCase , lowerCamelCase ) for lyr in self.encoders: __snake_case : List[Any] = lyr(lowerCamelCase , lowerCamelCase )[0] __snake_case : Union[str, Any] = self.layer_norm(lowerCamelCase ) return self.dropout_post(lowerCamelCase ), encoder_inputs_mask
81
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 _snake_case : Optional[Any] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[str] = ["pixel_values"] def __init__( self : List[Any] , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : int = 8 , **lowerCamelCase : Tuple , ) -> None: super().__init__(**lowerCamelCase ) __snake_case : Dict = do_rescale __snake_case : Dict = rescale_factor __snake_case : Optional[Any] = do_pad __snake_case : Tuple = pad_size def __snake_case ( self : Dict , lowerCamelCase : np.ndarray , lowerCamelCase : float , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Optional[int] ) -> np.ndarray: return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : int , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None ) -> Tuple: __snake_case , __snake_case : List[str] = get_image_size(lowerCamelCase ) __snake_case : Optional[Any] = (old_height // size + 1) * size - old_height __snake_case : List[Any] = (old_width // size + 1) * size - old_width return pad(lowerCamelCase , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCamelCase ) def __snake_case ( self : Tuple , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : Union[str, Any] , ) -> List[str]: __snake_case : int = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : str = do_pad if do_pad is not None else self.do_pad __snake_case : Any = pad_size if pad_size is not None else self.pad_size __snake_case : int = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __snake_case : str = [to_numpy_array(lowerCamelCase ) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_pad: __snake_case : Optional[Any] = [self.pad(lowerCamelCase , size=lowerCamelCase ) for image in images] __snake_case : int = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __snake_case : Union[str, Any] = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
81
1
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : str = logging.get_logger(__name__) _snake_case : Tuple = { "kakaobrain/align-base": "https://huggingface.co/kakaobrain/align-base/resolve/main/config.json", } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = "align_text_model" def __init__( self : Tuple , lowerCamelCase : Optional[Any]=30522 , lowerCamelCase : List[Any]=768 , lowerCamelCase : Any=12 , lowerCamelCase : Tuple=12 , lowerCamelCase : Dict=3072 , lowerCamelCase : Tuple="gelu" , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Union[str, Any]=0.1 , lowerCamelCase : Any=512 , lowerCamelCase : int=2 , lowerCamelCase : Union[str, Any]=0.02 , lowerCamelCase : Any=1E-12 , lowerCamelCase : Union[str, Any]=0 , lowerCamelCase : Optional[int]="absolute" , lowerCamelCase : List[str]=True , **lowerCamelCase : Dict , ) -> Optional[int]: super().__init__(**lowerCamelCase ) __snake_case : Optional[Any] = vocab_size __snake_case : List[str] = hidden_size __snake_case : Any = num_hidden_layers __snake_case : Optional[Any] = num_attention_heads __snake_case : List[Any] = hidden_act __snake_case : List[Any] = intermediate_size __snake_case : int = hidden_dropout_prob __snake_case : Union[str, Any] = attention_probs_dropout_prob __snake_case : Tuple = max_position_embeddings __snake_case : List[Any] = type_vocab_size __snake_case : List[Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : List[Any] = position_embedding_type __snake_case : List[Any] = use_cache __snake_case : str = pad_token_id @classmethod def __snake_case ( cls : List[str] , lowerCamelCase : Union[str, os.PathLike] , **lowerCamelCase : Any ) -> "PretrainedConfig": cls._set_token_in_kwargs(lowerCamelCase ) __snake_case , __snake_case : Union[str, Any] = cls.get_config_dict(lowerCamelCase , **lowerCamelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": __snake_case : int = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(lowerCamelCase , **lowerCamelCase ) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Any = "align_vision_model" def __init__( self : Dict , lowerCamelCase : int = 3 , lowerCamelCase : int = 600 , lowerCamelCase : float = 2.0 , lowerCamelCase : float = 3.1 , lowerCamelCase : int = 8 , lowerCamelCase : List[int] = [3, 3, 5, 3, 5, 5, 3] , lowerCamelCase : List[int] = [32, 16, 24, 40, 80, 112, 192] , lowerCamelCase : List[int] = [16, 24, 40, 80, 112, 192, 320] , lowerCamelCase : List[int] = [] , lowerCamelCase : List[int] = [1, 2, 2, 2, 1, 2, 1] , lowerCamelCase : List[int] = [1, 2, 2, 3, 3, 4, 1] , lowerCamelCase : List[int] = [1, 6, 6, 6, 6, 6, 6] , lowerCamelCase : float = 0.25 , lowerCamelCase : str = "swish" , lowerCamelCase : int = 2560 , lowerCamelCase : str = "mean" , lowerCamelCase : float = 0.02 , lowerCamelCase : float = 0.0_01 , lowerCamelCase : float = 0.99 , lowerCamelCase : float = 0.2 , **lowerCamelCase : Optional[Any] , ) -> List[Any]: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = num_channels __snake_case : int = image_size __snake_case : Any = width_coefficient __snake_case : List[Any] = depth_coefficient __snake_case : Any = depth_divisor __snake_case : Union[str, Any] = kernel_sizes __snake_case : Union[str, Any] = in_channels __snake_case : int = out_channels __snake_case : Tuple = depthwise_padding __snake_case : List[str] = strides __snake_case : Optional[int] = num_block_repeats __snake_case : Tuple = expand_ratios __snake_case : List[Any] = squeeze_expansion_ratio __snake_case : int = hidden_act __snake_case : int = hidden_dim __snake_case : List[str] = pooling_type __snake_case : Optional[int] = initializer_range __snake_case : str = batch_norm_eps __snake_case : Union[str, Any] = batch_norm_momentum __snake_case : Dict = drop_connect_rate __snake_case : Dict = sum(lowerCamelCase ) * 4 @classmethod def __snake_case ( cls : Any , lowerCamelCase : Union[str, os.PathLike] , **lowerCamelCase : int ) -> "PretrainedConfig": cls._set_token_in_kwargs(lowerCamelCase ) __snake_case , __snake_case : List[Any] = cls.get_config_dict(lowerCamelCase , **lowerCamelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": __snake_case : List[str] = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(lowerCamelCase , **lowerCamelCase ) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Dict = "align" __UpperCAmelCase : Optional[int] = True def __init__( self : str , lowerCamelCase : List[Any]=None , lowerCamelCase : Optional[Any]=None , lowerCamelCase : Tuple=640 , lowerCamelCase : List[Any]=1.0 , lowerCamelCase : Dict=0.02 , **lowerCamelCase : Tuple , ) -> str: super().__init__(**lowerCamelCase ) if text_config is None: __snake_case : Dict = {} logger.info("text_config is None. Initializing the AlignTextConfig with default values." ) if vision_config is None: __snake_case : Union[str, Any] = {} logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." ) __snake_case : Union[str, Any] = AlignTextConfig(**lowerCamelCase ) __snake_case : List[Any] = AlignVisionConfig(**lowerCamelCase ) __snake_case : List[Any] = projection_dim __snake_case : Optional[int] = temperature_init_value __snake_case : Any = initializer_range @classmethod def __snake_case ( cls : Union[str, Any] , lowerCamelCase : AlignTextConfig , lowerCamelCase : AlignVisionConfig , **lowerCamelCase : Tuple ) -> Any: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **lowerCamelCase ) def __snake_case ( self : str ) -> int: __snake_case : Optional[int] = copy.deepcopy(self.__dict__ ) __snake_case : List[Any] = self.text_config.to_dict() __snake_case : List[Any] = self.vision_config.to_dict() __snake_case : List[str] = self.__class__.model_type return output
81
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Any = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _snake_case : Any = { "configuration_chinese_clip": [ "CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "ChineseCLIPConfig", "ChineseCLIPOnnxConfig", "ChineseCLIPTextConfig", "ChineseCLIPVisionConfig", ], "processing_chinese_clip": ["ChineseCLIPProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : Dict = ["ChineseCLIPFeatureExtractor"] _snake_case : List[str] = ["ChineseCLIPImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "ChineseCLIPModel", "ChineseCLIPPreTrainedModel", "ChineseCLIPTextModel", "ChineseCLIPVisionModel", ] if TYPE_CHECKING: from .configuration_chinese_clip import ( CHINESE_CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, ChineseCLIPConfig, ChineseCLIPOnnxConfig, ChineseCLIPTextConfig, ChineseCLIPVisionConfig, ) from .processing_chinese_clip import ChineseCLIPProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_chinese_clip import ChineseCLIPFeatureExtractor, ChineseCLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_chinese_clip import ( CHINESE_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, ChineseCLIPModel, ChineseCLIPPreTrainedModel, ChineseCLIPTextModel, ChineseCLIPVisionModel, ) else: import sys _snake_case : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging _snake_case : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : CLIPSegForImageSegmentation , lowerCamelCase : CLIPSegProcessor , lowerCamelCase : AutoencoderKL , lowerCamelCase : CLIPTextModel , lowerCamelCase : CLIPTokenizer , lowerCamelCase : UNetaDConditionModel , lowerCamelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCamelCase : StableDiffusionSafetyChecker , lowerCamelCase : CLIPImageProcessor , ) -> Tuple: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __snake_case : Tuple = ( F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : Any = dict(scheduler.config ) __snake_case : List[Any] = 1 __snake_case : Tuple = FrozenDict(lowerCamelCase ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __snake_case : List[str] = ( F'The configuration file of this scheduler: {scheduler} has not set the configuration' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : List[str] = dict(scheduler.config ) __snake_case : List[str] = True __snake_case : Any = FrozenDict(lowerCamelCase ) if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=lowerCamelCase , segmentation_processor=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , ) def __snake_case ( self : Dict , lowerCamelCase : Optional[Union[str, int]] = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Any: self.enable_attention_slicing(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> str: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __snake_case : Optional[int] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase , lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : int ) -> Any: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any] , lowerCamelCase : Union[str, List[str]] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : str , lowerCamelCase : int = 512 , lowerCamelCase : int = 512 , lowerCamelCase : int = 50 , lowerCamelCase : float = 7.5 , lowerCamelCase : Optional[Union[str, List[str]]] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : float = 0.0 , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : Optional[torch.FloatTensor] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase : int = 1 , **lowerCamelCase : Dict , ) -> List[str]: __snake_case : Tuple = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __snake_case : str = self.segmentation_model(**lowerCamelCase ) __snake_case : Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __snake_case : List[Any] = self.numpy_to_pil(lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __snake_case : Tuple = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=lowerCamelCase , image=lowerCamelCase , mask_image=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , )
81
1
class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : str = "" , lowerCamelCase : bool = False ) -> None: # Mapping from the first character of the prefix of the node __snake_case : dict[str, RadixNode] = {} # A node will be a leaf if the tree contains its word __snake_case : int = is_leaf __snake_case : Union[str, Any] = prefix def __snake_case ( self : Tuple , lowerCamelCase : str ) -> tuple[str, str, str]: __snake_case : Any = 0 for q, w in zip(self.prefix , lowerCamelCase ): if q != w: break x += 1 return self.prefix[:x], self.prefix[x:], word[x:] def __snake_case ( self : int , lowerCamelCase : list[str] ) -> None: for word in words: self.insert(lowerCamelCase ) def __snake_case ( self : Tuple , lowerCamelCase : str ) -> None: # Case 1: If the word is the prefix of the node # Solution: We set the current node as leaf if self.prefix == word: __snake_case : Optional[int] = True # Case 2: The node has no edges that have a prefix to the word # Solution: We create an edge from the current node to a new one # containing the word elif word[0] not in self.nodes: __snake_case : Optional[Any] = RadixNode(prefix=lowerCamelCase , is_leaf=lowerCamelCase ) else: __snake_case : int = self.nodes[word[0]] __snake_case , __snake_case , __snake_case : Optional[Any] = incoming_node.match( lowerCamelCase ) # Case 3: The node prefix is equal to the matching # Solution: We insert remaining word on the next node if remaining_prefix == "": self.nodes[matching_string[0]].insert(lowerCamelCase ) # Case 4: The word is greater equal to the matching # Solution: Create a node in between both nodes, change # prefixes and add the new node for the remaining word else: __snake_case : List[Any] = remaining_prefix __snake_case : Dict = self.nodes[matching_string[0]] __snake_case : List[str] = RadixNode(lowerCamelCase , lowerCamelCase ) __snake_case : Dict = aux_node if remaining_word == "": __snake_case : Tuple = True else: self.nodes[matching_string[0]].insert(lowerCamelCase ) def __snake_case ( self : Optional[int] , lowerCamelCase : str ) -> bool: __snake_case : str = self.nodes.get(word[0] , lowerCamelCase ) if not incoming_node: return False else: __snake_case , __snake_case , __snake_case : str = incoming_node.match( lowerCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # This applies when the word and the prefix are equal elif remaining_word == "": return incoming_node.is_leaf # We have word remaining so we check the next node else: return incoming_node.find(lowerCamelCase ) def __snake_case ( self : Dict , lowerCamelCase : str ) -> bool: __snake_case : Any = self.nodes.get(word[0] , lowerCamelCase ) if not incoming_node: return False else: __snake_case , __snake_case , __snake_case : Dict = incoming_node.match( lowerCamelCase ) # If there is remaining prefix, the word can't be on the tree if remaining_prefix != "": return False # We have word remaining so we check the next node elif remaining_word != "": return incoming_node.delete(lowerCamelCase ) else: # If it is not a leaf, we don't have to delete if not incoming_node.is_leaf: return False else: # We delete the nodes if no edges go from it if len(incoming_node.nodes ) == 0: del self.nodes[word[0]] # We merge the current node with its only child if len(self.nodes ) == 1 and not self.is_leaf: __snake_case : Dict = list(self.nodes.values() )[0] __snake_case : Any = merging_node.is_leaf self.prefix += merging_node.prefix __snake_case : Tuple = merging_node.nodes # If there is more than 1 edge, we just mark it as non-leaf elif len(incoming_node.nodes ) > 1: __snake_case : Optional[int] = False # If there is 1 edge, we merge it with its child else: __snake_case : Dict = list(incoming_node.nodes.values() )[0] __snake_case : Optional[int] = merging_node.is_leaf incoming_node.prefix += merging_node.prefix __snake_case : List[str] = merging_node.nodes return True def __snake_case ( self : Any , lowerCamelCase : int = 0 ) -> None: if self.prefix != "": print("-" * height , self.prefix , " (leaf)" if self.is_leaf else "" ) for value in self.nodes.values(): value.print_tree(height + 1 ) def lowerCAmelCase_ ( ): __snake_case : Dict = "banana bananas bandana band apple all beast".split() __snake_case : int = RadixNode() root.insert_many(__lowerCamelCase ) assert all(root.find(__lowerCamelCase ) for word in words ) assert not root.find("bandanas" ) assert not root.find("apps" ) root.delete("all" ) assert not root.find("all" ) root.delete("banana" ) assert not root.find("banana" ) assert root.find("bananas" ) return True def lowerCAmelCase_ ( ): assert test_trie() def lowerCAmelCase_ ( ): __snake_case : Optional[Any] = RadixNode() __snake_case : Union[str, Any] = "banana bananas bandanas bandana band apple all beast".split() root.insert_many(__lowerCamelCase ) print("Words:" , __lowerCamelCase ) print("Tree:" ) root.print_tree() if __name__ == "__main__": main()
81
class a : """simple docstring""" def __init__( self : Tuple , lowerCamelCase : list ) -> None: __snake_case : str = set_counts __snake_case : Union[str, Any] = max(lowerCamelCase ) __snake_case : List[Any] = len(lowerCamelCase ) __snake_case : Tuple = [1] * num_sets __snake_case : Dict = list(range(lowerCamelCase ) ) def __snake_case ( self : str , lowerCamelCase : int , lowerCamelCase : int ) -> bool: __snake_case : List[Any] = self.get_parent(lowerCamelCase ) __snake_case : Tuple = self.get_parent(lowerCamelCase ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] __snake_case : List[str] = 0 __snake_case : List[Any] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __snake_case : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __snake_case : Union[str, Any] = 0 __snake_case : Optional[int] = src_parent __snake_case : Tuple = self.set_counts[src_parent] __snake_case : str = max(self.max_set , lowerCamelCase ) return True def __snake_case ( self : int , lowerCamelCase : int ) -> int: if self.parents[disj_set] == disj_set: return disj_set __snake_case : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
81
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Tuple = logging.get_logger(__name__) _snake_case : Optional[int] = { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json", } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = "mvp" __UpperCAmelCase : Optional[int] = ["past_key_values"] __UpperCAmelCase : Optional[Any] = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"} def __init__( self : Union[str, Any] , lowerCamelCase : str=50267 , lowerCamelCase : str=1024 , lowerCamelCase : Any=12 , lowerCamelCase : List[str]=4096 , lowerCamelCase : Dict=16 , lowerCamelCase : Optional[Any]=12 , lowerCamelCase : List[Any]=4096 , lowerCamelCase : Dict=16 , lowerCamelCase : Any=0.0 , lowerCamelCase : List[str]=0.0 , lowerCamelCase : Dict="gelu" , lowerCamelCase : Optional[Any]=1024 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : List[Any]=0.0 , lowerCamelCase : str=0.0 , lowerCamelCase : Any=0.02 , lowerCamelCase : Any=0.0 , lowerCamelCase : Dict=False , lowerCamelCase : Optional[Any]=True , lowerCamelCase : List[Any]=1 , lowerCamelCase : Tuple=0 , lowerCamelCase : Optional[int]=2 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Any=2 , lowerCamelCase : Union[str, Any]=2 , lowerCamelCase : Tuple=False , lowerCamelCase : str=100 , lowerCamelCase : int=800 , **lowerCamelCase : Optional[int] , ) -> Any: __snake_case : Tuple = vocab_size __snake_case : Union[str, Any] = max_position_embeddings __snake_case : Union[str, Any] = d_model __snake_case : List[str] = encoder_ffn_dim __snake_case : Tuple = encoder_layers __snake_case : Dict = encoder_attention_heads __snake_case : str = decoder_ffn_dim __snake_case : Optional[int] = decoder_layers __snake_case : Optional[int] = decoder_attention_heads __snake_case : List[str] = dropout __snake_case : Dict = attention_dropout __snake_case : int = activation_dropout __snake_case : Optional[int] = activation_function __snake_case : Any = init_std __snake_case : Any = encoder_layerdrop __snake_case : Optional[int] = decoder_layerdrop __snake_case : Dict = classifier_dropout __snake_case : Union[str, Any] = use_cache __snake_case : List[Any] = encoder_layers __snake_case : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True __snake_case : List[str] = use_prompt __snake_case : Union[str, Any] = prompt_length __snake_case : int = prompt_mid_dim super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , forced_eos_token_id=lowerCamelCase , **lowerCamelCase , ) if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated" , lowerCamelCase ): __snake_case : Any = self.bos_token_id warnings.warn( F'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ' "The config can simply be saved and uploaded again to be fixed." )
81
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : int , lowerCamelCase : Any , lowerCamelCase : int=7 , lowerCamelCase : str=3 , lowerCamelCase : Optional[int]=30 , lowerCamelCase : Dict=400 , lowerCamelCase : str=True , lowerCamelCase : str=None , lowerCamelCase : Any=True , lowerCamelCase : Union[str, Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[int]=1 / 255 , lowerCamelCase : Any=True , ) -> str: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __snake_case : Optional[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __snake_case : Optional[Any] = parent __snake_case : List[Any] = batch_size __snake_case : Optional[int] = num_channels __snake_case : str = min_resolution __snake_case : int = max_resolution __snake_case : int = do_resize __snake_case : Tuple = size __snake_case : Any = do_normalize __snake_case : int = image_mean __snake_case : Tuple = image_std __snake_case : Dict = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : str = do_pad def __snake_case ( self : Any ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __snake_case ( self : Dict , lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any]=False ) -> List[str]: if not batched: __snake_case : Dict = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : Dict = image.size else: __snake_case , __snake_case : List[str] = image.shape[1], image.shape[2] if w < h: __snake_case : Optional[int] = int(self.size["shortest_edge"] * h / w ) __snake_case : int = self.size["shortest_edge"] elif w > h: __snake_case : List[str] = self.size["shortest_edge"] __snake_case : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: __snake_case : List[Any] = self.size["shortest_edge"] __snake_case : Any = self.size["shortest_edge"] else: __snake_case : int = [] for image in image_inputs: __snake_case , __snake_case : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Optional[Any] = ConditionalDetrImageProcessingTester(self ) @property def __snake_case ( self : Any ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any] ) -> Optional[int]: __snake_case : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def __snake_case ( self : Any ) -> Dict: __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) __snake_case : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> Dict: pass def __snake_case ( self : Tuple ) -> str: # Initialize image_processing __snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __snake_case : Dict = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> str: # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : List[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> List[str]: # Initialize image_processing __snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : List[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : int = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __snake_case ( self : Any ) -> Optional[int]: # prepare image and target __snake_case : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : List[Any] = {"image_id": 39769, "annotations": target} # encode them __snake_case : List[str] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __snake_case : List[str] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Optional[int] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : List[Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Optional[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __snake_case : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Tuple = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> Tuple: # prepare image, target and masks_path __snake_case : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : str = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} __snake_case : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __snake_case : int = ConditionalDetrImageProcessor(format="coco_panoptic" ) __snake_case : str = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : Any = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : int = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __snake_case : List[Any] = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __snake_case : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
81
1
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Optional[Any] = {"configuration_timm_backbone": ["TimmBackboneConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["TimmBackbone"] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys _snake_case : List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _snake_case : Optional[Any] = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _snake_case : Dict = "UperNetConfig" class a (nn.Module ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : Union[int, Tuple[int, int]] , lowerCamelCase : Union[int, Tuple[int, int], str] = 0 , lowerCamelCase : bool = False , lowerCamelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() __snake_case : Union[str, Any] = nn.Convad( in_channels=lowerCamelCase , out_channels=lowerCamelCase , kernel_size=lowerCamelCase , padding=lowerCamelCase , bias=lowerCamelCase , dilation=lowerCamelCase , ) __snake_case : Dict = nn.BatchNormad(lowerCamelCase ) __snake_case : List[Any] = nn.ReLU() def __snake_case ( self : List[Any] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : Dict = self.conv(lowerCamelCase ) __snake_case : int = self.batch_norm(lowerCamelCase ) __snake_case : Optional[Any] = self.activation(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : str , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ) -> None: super().__init__() __snake_case : Tuple = [ nn.AdaptiveAvgPoolad(lowerCamelCase ), UperNetConvModule(lowerCamelCase , lowerCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : Dict , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : List[str] = input for layer in self.layers: __snake_case : Tuple = layer(lowerCamelCase ) return hidden_state class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple[int, ...] , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : bool ) -> None: super().__init__() __snake_case : Dict = pool_scales __snake_case : List[str] = align_corners __snake_case : List[Any] = in_channels __snake_case : str = channels __snake_case : Optional[Any] = [] for i, pool_scale in enumerate(lowerCamelCase ): __snake_case : Union[str, Any] = UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase , in_channels=lowerCamelCase , channels=lowerCamelCase ) self.blocks.append(lowerCamelCase ) self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> List[torch.Tensor]: __snake_case : Tuple = [] for ppm in self.blocks: __snake_case : Any = ppm(lowerCamelCase ) __snake_case : List[Any] = nn.functional.interpolate( lowerCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(lowerCamelCase ) return ppm_outs class a (nn.Module ): """simple docstring""" def __init__( self : int , lowerCamelCase : str , lowerCamelCase : str ) -> List[str]: super().__init__() __snake_case : Dict = config __snake_case : List[str] = config.pool_scales # e.g. (1, 2, 3, 6) __snake_case : Tuple = in_channels __snake_case : str = config.hidden_size __snake_case : List[str] = False __snake_case : Any = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __snake_case : Tuple = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __snake_case : List[str] = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __snake_case : List[Any] = nn.ModuleList() __snake_case : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __snake_case : Union[str, Any] = UperNetConvModule(lowerCamelCase , self.channels , kernel_size=1 ) __snake_case : Optional[int] = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(lowerCamelCase ) self.fpn_convs.append(lowerCamelCase ) __snake_case : int = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def __snake_case ( self : List[str] ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> str: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : List[Any] , lowerCamelCase : Tuple ) -> Optional[int]: __snake_case : str = inputs[-1] __snake_case : int = [x] psp_outs.extend(self.psp_modules(lowerCamelCase ) ) __snake_case : Tuple = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Union[str, Any] = self.bottleneck(lowerCamelCase ) return output def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # build laterals __snake_case : Any = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(lowerCamelCase ) ) # build top-down path __snake_case : Dict = len(lowerCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Union[str, Any] = laterals[i - 1].shape[2:] __snake_case : Optional[int] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=lowerCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs __snake_case : str = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Tuple = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) __snake_case : str = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Optional[Any] = self.fpn_bottleneck(lowerCamelCase ) __snake_case : Tuple = self.classifier(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int = 2 , lowerCamelCase : int = 3 , lowerCamelCase : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() __snake_case : List[Any] = config __snake_case : List[str] = config.auxiliary_in_channels __snake_case : List[Any] = config.auxiliary_channels __snake_case : Tuple = config.auxiliary_num_convs __snake_case : int = config.auxiliary_concat_input __snake_case : Optional[int] = in_index __snake_case : Tuple = (kernel_size // 2) * dilation __snake_case : Optional[int] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) if self.num_convs == 0: __snake_case : Union[str, Any] = nn.Identity() else: __snake_case : Any = nn.Sequential(*lowerCamelCase ) if self.concat_input: __snake_case : int = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=lowerCamelCase , padding=kernel_size // 2 ) __snake_case : Optional[Any] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def __snake_case ( self : Dict ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : Tuple ) -> Optional[int]: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : Optional[int] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps __snake_case : List[str] = encoder_hidden_states[self.in_index] __snake_case : Optional[Any] = self.convs(lowerCamelCase ) if self.concat_input: __snake_case : Optional[Any] = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __snake_case : Union[str, Any] = self.classifier(lowerCamelCase ) return output class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = UperNetConfig __UpperCAmelCase : int = "pixel_values" __UpperCAmelCase : str = True def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> List[Any]: if isinstance(lowerCamelCase , lowerCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def __snake_case ( self : Optional[Any] ) -> List[str]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def __snake_case ( self : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[Any]=False ) -> Dict: if isinstance(lowerCamelCase , lowerCamelCase ): __snake_case : Union[str, Any] = value _snake_case : Dict = R"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _snake_case : Tuple = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , _lowerCAmelCase , ) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Dict , lowerCamelCase : int ) -> Optional[int]: super().__init__(lowerCamelCase ) __snake_case : Any = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __snake_case : Union[str, Any] = UperNetHead(lowerCamelCase , in_channels=self.backbone.channels ) __snake_case : Any = UperNetFCNHead(lowerCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: __snake_case : Any = return_dict if return_dict is not None else self.config.use_return_dict __snake_case : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case : str = output_attentions if output_attentions is not None else self.config.output_attentions __snake_case : Tuple = self.backbone.forward_with_filtered_kwargs( lowerCamelCase , output_hidden_states=lowerCamelCase , output_attentions=lowerCamelCase ) __snake_case : List[Any] = outputs.feature_maps __snake_case : List[Any] = self.decode_head(lowerCamelCase ) __snake_case : List[str] = nn.functional.interpolate(lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : Optional[int] = None if self.auxiliary_head is not None: __snake_case : Dict = self.auxiliary_head(lowerCamelCase ) __snake_case : Dict = nn.functional.interpolate( lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : int = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss __snake_case : Any = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __snake_case : Union[str, Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __snake_case : Any = (logits,) + outputs[1:] else: __snake_case : str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
81
1
from collections.abc import Iterable from typing import Generic, TypeVar _snake_case : Dict = TypeVar("_T") class a (Generic[_T] ): """simple docstring""" def __init__( self : int , lowerCamelCase : Iterable[_T] | None = None ) -> None: __snake_case : list[_T] = list(iterable or [] ) __snake_case : list[_T] = [] def __len__( self : Optional[int] ) -> int: return len(self._stacka ) + len(self._stacka ) def __repr__( self : Tuple ) -> str: return F'Queue({tuple(self._stacka[::-1] + self._stacka )})' def __snake_case ( self : Tuple , lowerCamelCase : _T ) -> None: self._stacka.append(lowerCamelCase ) def __snake_case ( self : str ) -> _T: __snake_case : List[str] = self._stacka.pop __snake_case : int = self._stacka.append if not self._stacka: while self._stacka: stacka_append(stacka_pop() ) if not self._stacka: raise IndexError("Queue is empty" ) return self._stacka.pop() if __name__ == "__main__": from doctest import testmod testmod()
81
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase ): if not nums: return 0 __snake_case : Any = nums[0] __snake_case : str = 0 for num in nums[1:]: __snake_case , __snake_case : List[str] = ( max_excluding + num, max(__lowerCamelCase , __lowerCamelCase ), ) return max(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
81
1
import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor _snake_case : Dict = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : str , *lowerCamelCase : int , **lowerCamelCase : List[str] ) -> None: warnings.warn( "The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use PoolFormerImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
from __future__ import annotations from typing import Any def lowerCAmelCase_ ( __lowerCamelCase ): create_state_space_tree(__lowerCamelCase , [] , 0 ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == len(__lowerCamelCase ): print(__lowerCamelCase ) return create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _snake_case : list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
81
1
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class a (_lowerCAmelCase ): """simple docstring""" @slow @require_torch def __snake_case ( self : Any ) -> Union[str, Any]: __snake_case : Optional[int] = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) __snake_case : int = BertTokenizer.from_pretrained("bert-base-uncased" ) __snake_case : List[str] = bertabert.config.encoder.vocab_size __snake_case : Dict = tokenizer.sep_token_id __snake_case : Dict = tokenizer.cls_token_id __snake_case : List[Any] = 128 __snake_case : Optional[int] = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) __snake_case : str = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) __snake_case : str = train_dataset.select(range(32 ) ) __snake_case : Union[str, Any] = val_dataset.select(range(16 ) ) __snake_case : Union[str, Any] = 4 def _map_to_encoder_decoder_inputs(lowerCamelCase : int ): # Tokenizer will automatically set [BOS] <text> [EOS] __snake_case : Any = tokenizer(batch["article"] , padding="max_length" , truncation=lowerCamelCase , max_length=512 ) __snake_case : Dict = tokenizer(batch["highlights"] , padding="max_length" , truncation=lowerCamelCase , max_length=128 ) __snake_case : Optional[Any] = inputs.input_ids __snake_case : List[str] = inputs.attention_mask __snake_case : List[Any] = outputs.input_ids __snake_case : Dict = outputs.input_ids.copy() __snake_case : Tuple = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] __snake_case : str = outputs.attention_mask assert all(len(lowerCamelCase ) == 512 for x in inputs.input_ids ) assert all(len(lowerCamelCase ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(lowerCamelCase : Optional[Any] ): __snake_case : List[str] = pred.label_ids __snake_case : int = pred.predictions # all unnecessary tokens are removed __snake_case : List[Any] = tokenizer.batch_decode(lowerCamelCase , skip_special_tokens=lowerCamelCase ) __snake_case : Dict = tokenizer.batch_decode(lowerCamelCase , skip_special_tokens=lowerCamelCase ) __snake_case : str = sum([int(pred_str[i] == label_str[i] ) for i in range(len(lowerCamelCase ) )] ) / len(lowerCamelCase ) return {"accuracy": accuracy} # map train dataset __snake_case : Tuple = train_dataset.map( _map_to_encoder_decoder_inputs , batched=lowerCamelCase , batch_size=lowerCamelCase , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset __snake_case : Dict = val_dataset.map( _map_to_encoder_decoder_inputs , batched=lowerCamelCase , batch_size=lowerCamelCase , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) __snake_case : Optional[int] = self.get_auto_remove_tmp_dir() __snake_case : int = SeqaSeqTrainingArguments( output_dir=lowerCamelCase , per_device_train_batch_size=lowerCamelCase , per_device_eval_batch_size=lowerCamelCase , predict_with_generate=lowerCamelCase , evaluation_strategy="steps" , do_train=lowerCamelCase , do_eval=lowerCamelCase , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer __snake_case : Optional[int] = SeqaSeqTrainer( model=lowerCamelCase , args=lowerCamelCase , compute_metrics=_compute_metrics , train_dataset=lowerCamelCase , eval_dataset=lowerCamelCase , tokenizer=lowerCamelCase , ) # start training trainer.train()
81
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
1
import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class a : """simple docstring""" @staticmethod def __snake_case ( *lowerCamelCase : List[str] , **lowerCamelCase : Optional[int] ) -> Union[str, Any]: pass @is_pipeline_test @require_vision @require_torch class a (unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Any = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def __snake_case ( self : Optional[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Optional[int] , lowerCamelCase : Any ) -> Any: __snake_case : List[str] = pipeline( "zero-shot-object-detection" , model="hf-internal-testing/tiny-random-owlvit-object-detection" ) __snake_case : Dict = [ { "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", "candidate_labels": ["cat", "remote", "couch"], } ] return object_detector, examples def __snake_case ( self : Tuple , lowerCamelCase : Tuple , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Dict = object_detector(examples[0] , threshold=0.0 ) __snake_case : Optional[int] = len(lowerCamelCase ) self.assertGreater(lowerCamelCase , 0 ) self.assertEqual( lowerCamelCase , [ { "score": ANY(lowerCamelCase ), "label": ANY(lowerCamelCase ), "box": {"xmin": ANY(lowerCamelCase ), "ymin": ANY(lowerCamelCase ), "xmax": ANY(lowerCamelCase ), "ymax": ANY(lowerCamelCase )}, } for i in range(lowerCamelCase ) ] , ) @require_tf @unittest.skip("Zero Shot Object Detection not implemented in TF" ) def __snake_case ( self : Optional[int] ) -> List[str]: pass @require_torch def __snake_case ( self : Any ) -> str: __snake_case : List[Any] = pipeline( "zero-shot-object-detection" , model="hf-internal-testing/tiny-random-owlvit-object-detection" ) __snake_case : Optional[Any] = object_detector( "./tests/fixtures/tests_samples/COCO/000000039769.png" , candidate_labels=["cat", "remote", "couch"] , threshold=0.64 , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ {"score": 0.72_35, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.72_18, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.71_84, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.67_48, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.66_56, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.66_14, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.64_56, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, {"score": 0.6_42, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, {"score": 0.64_19, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, ] , ) __snake_case : str = object_detector( [ { "image": "./tests/fixtures/tests_samples/COCO/000000039769.png", "candidate_labels": ["cat", "remote", "couch"], } ] , threshold=0.64 , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ [ {"score": 0.72_35, "label": "cat", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.72_18, "label": "remote", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.71_84, "label": "couch", "box": {"xmin": 204, "ymin": 167, "xmax": 232, "ymax": 190}}, {"score": 0.67_48, "label": "remote", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.66_56, "label": "cat", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.66_14, "label": "couch", "box": {"xmin": 571, "ymin": 83, "xmax": 598, "ymax": 103}}, {"score": 0.64_56, "label": "remote", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, {"score": 0.6_42, "label": "remote", "box": {"xmin": 67, "ymin": 274, "xmax": 93, "ymax": 297}}, {"score": 0.64_19, "label": "cat", "box": {"xmin": 494, "ymin": 105, "xmax": 521, "ymax": 127}}, ] ] , ) @require_torch @slow def __snake_case ( self : Union[str, Any] ) -> Tuple: __snake_case : int = pipeline("zero-shot-object-detection" ) __snake_case : Optional[Any] = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ {"score": 0.28_68, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.2_77, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.25_37, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.14_74, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.12_08, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ] , ) __snake_case : Optional[int] = object_detector( [ { "image": "http://images.cocodataset.org/val2017/000000039769.jpg", "candidate_labels": ["cat", "remote", "couch"], }, { "image": "http://images.cocodataset.org/val2017/000000039769.jpg", "candidate_labels": ["cat", "remote", "couch"], }, ] , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ [ {"score": 0.28_68, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.2_77, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.25_37, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.14_74, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.12_08, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ], [ {"score": 0.28_68, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.2_77, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.25_37, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, {"score": 0.14_74, "label": "remote", "box": {"xmin": 335, "ymin": 74, "xmax": 371, "ymax": 187}}, {"score": 0.12_08, "label": "couch", "box": {"xmin": 4, "ymin": 0, "xmax": 642, "ymax": 476}}, ], ] , ) @require_tf @unittest.skip("Zero Shot Object Detection not implemented in TF" ) def __snake_case ( self : Optional[Any] ) -> int: pass @require_torch @slow def __snake_case ( self : Optional[int] ) -> Any: __snake_case : List[Any] = 0.2 __snake_case : Any = pipeline("zero-shot-object-detection" ) __snake_case : Optional[Any] = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , threshold=lowerCamelCase , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ {"score": 0.28_68, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.2_77, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, {"score": 0.25_37, "label": "cat", "box": {"xmin": 1, "ymin": 55, "xmax": 315, "ymax": 472}}, ] , ) @require_torch @slow def __snake_case ( self : int ) -> Union[str, Any]: __snake_case : str = 2 __snake_case : str = pipeline("zero-shot-object-detection" ) __snake_case : int = object_detector( "http://images.cocodataset.org/val2017/000000039769.jpg" , candidate_labels=["cat", "remote", "couch"] , top_k=lowerCamelCase , ) self.assertEqual( nested_simplify(lowerCamelCase , decimals=4 ) , [ {"score": 0.28_68, "label": "cat", "box": {"xmin": 324, "ymin": 20, "xmax": 640, "ymax": 373}}, {"score": 0.2_77, "label": "remote", "box": {"xmin": 40, "ymin": 72, "xmax": 177, "ymax": 115}}, ] , )
81
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 a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).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() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).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() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = 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 __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = 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": __snake_case : Union[str, Any] = 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": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
1
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> int: with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights __snake_case : List[Any] = FlaxDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe" , safety_checker=lowerCamelCase , cache_dir=lowerCamelCase ) __snake_case : int = [t[-1] for t in os.walk(os.path.join(lowerCamelCase , os.listdir(lowerCamelCase )[0] , "snapshots" ) )] __snake_case : Any = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(".bin" ) for f in files ) @slow @require_flax class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : str ) -> Tuple: __snake_case , __snake_case : Any = FlaxStableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe" , safety_checker=lowerCamelCase ) __snake_case : Dict = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : Dict = jax.random.PRNGKey(0 ) __snake_case : Any = 4 __snake_case : Tuple = jax.device_count() __snake_case : List[Any] = num_samples * [prompt] __snake_case : Tuple = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __snake_case : int = replicate(lowerCamelCase ) __snake_case : List[Any] = jax.random.split(lowerCamelCase , lowerCamelCase ) __snake_case : Union[str, Any] = shard(lowerCamelCase ) __snake_case : Union[str, Any] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1_51_47_45 ) < 1E-3 assert np.abs(np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 4_99_47.8_75 ) < 5E-1 __snake_case : str = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(lowerCamelCase ) == num_samples def __snake_case ( self : Dict ) -> Optional[int]: __snake_case , __snake_case : List[Any] = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="flax" , safety_checker=lowerCamelCase ) __snake_case : Optional[int] = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : int = jax.random.PRNGKey(0 ) __snake_case : Any = 50 __snake_case : str = jax.device_count() __snake_case : Tuple = num_samples * [prompt] __snake_case : str = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __snake_case : List[str] = replicate(lowerCamelCase ) __snake_case : Optional[Any] = jax.random.split(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = shard(lowerCamelCase ) __snake_case : int = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05_65_24_01) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_38_38_08.2) ) < 5E-1 def __snake_case ( self : int ) -> int: __snake_case , __snake_case : Any = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase ) __snake_case : List[str] = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : Union[str, Any] = jax.random.PRNGKey(0 ) __snake_case : List[str] = 50 __snake_case : List[Any] = jax.device_count() __snake_case : Optional[int] = num_samples * [prompt] __snake_case : Optional[int] = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __snake_case : str = replicate(lowerCamelCase ) __snake_case : Optional[Any] = jax.random.split(lowerCamelCase , lowerCamelCase ) __snake_case : int = shard(lowerCamelCase ) __snake_case : List[str] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def __snake_case ( self : List[str] ) -> List[Any]: __snake_case , __snake_case : str = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa ) __snake_case : Optional[Any] = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : str = jax.random.PRNGKey(0 ) __snake_case : Any = 50 __snake_case : Optional[Any] = jax.device_count() __snake_case : Optional[int] = num_samples * [prompt] __snake_case : int = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __snake_case : int = replicate(lowerCamelCase ) __snake_case : Optional[Any] = jax.random.split(lowerCamelCase , lowerCamelCase ) __snake_case : Dict = shard(lowerCamelCase ) __snake_case : List[str] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04_00_39_06) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_37_35_16.75) ) < 5E-1 def __snake_case ( self : Dict ) -> Union[str, Any]: __snake_case : Union[str, Any] = FlaxDDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , set_alpha_to_one=lowerCamelCase , steps_offset=1 , ) __snake_case , __snake_case : Optional[Any] = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , ) __snake_case : Any = scheduler.create_state() __snake_case : int = scheduler_state __snake_case : Any = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : Union[str, Any] = jax.random.PRNGKey(0 ) __snake_case : Tuple = 50 __snake_case : Any = jax.device_count() __snake_case : Optional[Any] = num_samples * [prompt] __snake_case : Optional[Any] = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __snake_case : Optional[int] = replicate(lowerCamelCase ) __snake_case : str = jax.random.split(lowerCamelCase , lowerCamelCase ) __snake_case : List[str] = shard(lowerCamelCase ) __snake_case : Optional[int] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_45_04_39_45) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2_34_76_93.5) ) < 5E-1 def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Optional[int] = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __snake_case : Optional[Any] = jax.device_count() __snake_case : Tuple = num_samples * [prompt] __snake_case : List[str] = jax.random.split(jax.random.PRNGKey(0 ) , lowerCamelCase ) __snake_case , __snake_case : Any = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , ) __snake_case : str = replicate(lowerCamelCase ) __snake_case : Union[str, Any] = pipeline.prepare_inputs(lowerCamelCase ) __snake_case : int = shard(lowerCamelCase ) __snake_case : Tuple = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) __snake_case : List[Any] = images[2, 0, 256, 10:17, 1] # With memory efficient attention __snake_case , __snake_case : Union[str, Any] = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , use_memory_efficient_attention=lowerCamelCase , ) __snake_case : str = replicate(lowerCamelCase ) __snake_case : int = pipeline.prepare_inputs(lowerCamelCase ) __snake_case : List[Any] = shard(lowerCamelCase ) __snake_case : Optional[Any] = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) __snake_case : str = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
81
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _snake_case : Optional[int] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[Any] , *lowerCamelCase : Any , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
# 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 subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file _snake_case : Dict = "Run commands across TPU VMs for initial setup before running `accelerate launch`." def lowerCAmelCase_ ( __lowerCamelCase=None ): if subparsers is not None: __snake_case : Optional[Any] = subparsers.add_parser("tpu-config" , description=_description ) else: __snake_case : List[Any] = argparse.ArgumentParser("Accelerate tpu-config command" , description=_description ) # Core arguments __snake_case : Any = parser.add_argument_group( "Config Arguments" , "Arguments that can be configured through `accelerate config`." ) config_args.add_argument( "--config_file" , type=__lowerCamelCase , default=__lowerCamelCase , help="Path to the config file to use for accelerate." , ) config_args.add_argument( "--tpu_name" , default=__lowerCamelCase , help="The name of the TPU to use. If not specified, will use the TPU specified in the config file." , ) config_args.add_argument( "--tpu_zone" , default=__lowerCamelCase , help="The zone of the TPU to use. If not specified, will use the zone specified in the config file." , ) __snake_case : Union[str, Any] = parser.add_argument_group("TPU Arguments" , "Arguments for options ran inside the TPU." ) pod_args.add_argument( "--use_alpha" , action="store_true" , help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`." , ) pod_args.add_argument( "--command_file" , default=__lowerCamelCase , help="The path to the file containing the commands to run on the pod on startup." , ) pod_args.add_argument( "--command" , action="append" , nargs="+" , help="A command to run on the pod. Can be passed multiple times." , ) pod_args.add_argument( "--install_accelerate" , action="store_true" , help="Whether to install accelerate on the pod. Defaults to False." , ) pod_args.add_argument( "--accelerate_version" , default="latest" , help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub." , ) pod_args.add_argument( "--debug" , action="store_true" , help="If set, will print the command that would be run instead of running it." ) if subparsers is not None: parser.set_defaults(func=__lowerCamelCase ) return parser def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(__lowerCamelCase ): __snake_case : str = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: __snake_case : List[str] = defaults.command_file if not args.command and defaults.commands is not None: __snake_case : Optional[Any] = defaults.commands if not args.tpu_name: __snake_case : Optional[int] = defaults.tpu_name if not args.tpu_zone: __snake_case : Union[str, Any] = defaults.tpu_zone if args.accelerate_version == "dev": __snake_case : List[Any] = "git+https://github.com/huggingface/accelerate.git" elif args.accelerate_version == "latest": __snake_case : Optional[int] = "accelerate -U" elif isinstance(parse(args.accelerate_version ) , __lowerCamelCase ): __snake_case : Dict = F'accelerate=={args.accelerate_version}' if not args.command_file and not args.command: raise ValueError("You must specify either a command file or a command to run on the pod." ) if args.command_file: with open(args.command_file , "r" ) as f: __snake_case : int = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , __lowerCamelCase ): __snake_case : str = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate __snake_case : int = ["cd /usr/share"] if args.install_accelerate: new_cmd += [F'pip install {args.accelerate_version}'] new_cmd += args.command __snake_case : Any = "; ".join(__lowerCamelCase ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess __snake_case : Any = ["gcloud"] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(F'Running {" ".join(__lowerCamelCase )}' ) return subprocess.run(__lowerCamelCase ) print("Successfully setup pod." ) def lowerCAmelCase_ ( ): __snake_case : Tuple = tpu_command_parser() __snake_case : List[Any] = parser.parse_args() tpu_command_launcher(__lowerCamelCase )
81
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Any = SamImageProcessor() __snake_case : Optional[int] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Optional[int] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : int ) -> List[Any]: __snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[Any] ) -> Dict: __snake_case : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : List[str] ) -> Tuple: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Optional[int] = self.prepare_image_inputs() __snake_case : List[str] = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : Dict = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Tuple = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[str] = [torch.ones((1, 3, 5, 5) )] __snake_case : Tuple = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : int = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , torch.tensor(lowerCamelCase ) , torch.tensor(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : List[str] = [np.ones((1, 3, 5, 5) )] __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : str = [[1, 0], [0, 1]] with self.assertRaises(lowerCamelCase ): __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) @require_vision @require_tf class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : int = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : str , **lowerCamelCase : Any ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : Dict = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : int ) -> List[str]: __snake_case : List[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: __snake_case : str = self.get_image_processor() __snake_case : Union[str, Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : int = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : List[str] = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def __snake_case ( self : Any ) -> Optional[int]: __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Union[str, Any] = [tf.ones((1, 3, 5, 5) )] __snake_case : List[Any] = [[1764, 2646]] __snake_case : Dict = [[683, 1024]] __snake_case : List[str] = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , tf.convert_to_tensor(lowerCamelCase ) , tf.convert_to_tensor(lowerCamelCase ) , return_tensors="tf" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : Union[str, Any] = [np.ones((1, 3, 5, 5) )] __snake_case : List[str] = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Tuple = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __snake_case : Dict = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[str] , **lowerCamelCase : Any ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : str = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __snake_case : Dict = [tf.convert_to_tensor(lowerCamelCase )] __snake_case : List[Any] = [torch.tensor(lowerCamelCase )] __snake_case : Optional[Any] = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : Union[str, Any] = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) __snake_case : Dict = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : Any = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : Any = image_processor(lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Optional[Any] = processor(images=lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Tuple = image_processor(lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() __snake_case : List[Any] = processor(images=lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) )
81
1
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowerCamelCase : str , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
_snake_case : Optional[Any] = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" _snake_case : Union[str, Any] = [{"type": "code", "content": INSTALL_CONTENT}] _snake_case : Optional[Any] = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
81
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case : Union[str, Any] = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["OwlViTFeatureExtractor"] _snake_case : Optional[int] = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _snake_case : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
import doctest from collections import deque import numpy as np class a : """simple docstring""" def __init__( self : List[str] ) -> None: __snake_case : List[Any] = [2, 1, 2, -1] __snake_case : Union[str, Any] = [1, 2, 3, 4] def __snake_case ( self : int ) -> list[float]: __snake_case : int = len(self.first_signal ) __snake_case : Union[str, Any] = len(self.second_signal ) __snake_case : Any = max(lowerCamelCase , lowerCamelCase ) # create a zero matrix of max_length x max_length __snake_case : str = [[0] * max_length for i in range(lowerCamelCase )] # fills the smaller signal with zeros to make both signals of same length if length_first_signal < length_second_signal: self.first_signal += [0] * (max_length - length_first_signal) elif length_first_signal > length_second_signal: self.second_signal += [0] * (max_length - length_second_signal) for i in range(lowerCamelCase ): __snake_case : Tuple = deque(self.second_signal ) rotated_signal.rotate(lowerCamelCase ) for j, item in enumerate(lowerCamelCase ): matrix[i][j] += item # multiply the matrix with the first signal __snake_case : Optional[int] = np.matmul(np.transpose(lowerCamelCase ) , np.transpose(self.first_signal ) ) # rounding-off to two decimal places return [round(lowerCamelCase , 2 ) for i in final_signal] if __name__ == "__main__": doctest.testmod()
81
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : str = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "van" def __init__( self : Optional[int] , lowerCamelCase : Any=224 , lowerCamelCase : str=3 , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : Dict=[4, 2, 2, 2] , lowerCamelCase : List[Any]=[64, 128, 320, 512] , lowerCamelCase : str=[3, 3, 12, 3] , lowerCamelCase : Dict=[8, 8, 4, 4] , lowerCamelCase : Any="gelu" , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Tuple=1E-6 , lowerCamelCase : Optional[int]=1E-2 , lowerCamelCase : int=0.0 , lowerCamelCase : Optional[Any]=0.0 , **lowerCamelCase : Optional[int] , ) -> int: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = image_size __snake_case : Any = num_channels __snake_case : Any = patch_sizes __snake_case : List[Any] = strides __snake_case : str = hidden_sizes __snake_case : Dict = depths __snake_case : Optional[int] = mlp_ratios __snake_case : Dict = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : Optional[int] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : int = dropout_rate
81
1
import torch def lowerCAmelCase_ ( ): if torch.cuda.is_available(): __snake_case : int = torch.cuda.device_count() else: __snake_case : Tuple = 0 print(F'Successfully ran on {num_gpus} GPUs' ) if __name__ == "__main__": main()
81
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case : Union[str, Any] = logging.getLogger(__name__) def lowerCAmelCase_ ( ): __snake_case : int = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __snake_case : List[str] = parser.parse_args() return args def lowerCAmelCase_ ( __lowerCamelCase ): def fn(__lowerCamelCase ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = [] for i in range(len(tokenized_data["input_ids"] ) ): __snake_case : Tuple = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase ) __snake_case : str = tf.train.Example(features=__lowerCamelCase ) __snake_case : List[str] = example.SerializeToString() records.append(__lowerCamelCase ) return records def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) __snake_case : Dict = dataset.select(range(__lowerCamelCase ) ) print(F'Limiting the dataset to {args.limit} entries.' ) __snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __snake_case : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: __snake_case : str = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __snake_case : Any = tokenize_function(__lowerCamelCase ) __snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__lowerCamelCase ): # Concatenate all texts. __snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()} __snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __snake_case : int = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result __snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 ) __snake_case : Optional[Any] = 0 __snake_case : Optional[Any] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): __snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size] __snake_case : Any = len(dataset_snapshot["input_ids"] ) __snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' ) __snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): __snake_case : Union[str, Any] = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase ) if __name__ == "__main__": _snake_case : List[Any] = parse_args() main(args)
81
1
import copy from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import TensorType, logging _snake_case : Tuple = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[int] = ["input_features"] def __init__( self : int , lowerCamelCase : str=80 , lowerCamelCase : List[Any]=16000 , lowerCamelCase : Dict=160 , lowerCamelCase : int=30 , lowerCamelCase : Any=400 , lowerCamelCase : Optional[Any]=0.0 , lowerCamelCase : Any=False , **lowerCamelCase : Optional[Any] , ) -> Dict: super().__init__( feature_size=lowerCamelCase , sampling_rate=lowerCamelCase , padding_value=lowerCamelCase , return_attention_mask=lowerCamelCase , **lowerCamelCase , ) __snake_case : Union[str, Any] = n_fft __snake_case : List[Any] = hop_length __snake_case : Optional[Any] = chunk_length __snake_case : List[str] = chunk_length * sampling_rate __snake_case : str = self.n_samples // hop_length __snake_case : Any = sampling_rate __snake_case : Dict = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=lowerCamelCase , min_frequency=0.0 , max_frequency=80_00.0 , sampling_rate=lowerCamelCase , norm="slaney" , mel_scale="slaney" , ) def __snake_case ( self : List[Any] , lowerCamelCase : np.array ) -> np.ndarray: __snake_case : Union[str, Any] = spectrogram( lowerCamelCase , window_function(self.n_fft , "hann" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters , log_mel="log10" , ) __snake_case : Dict = log_spec[:, :-1] __snake_case : Any = np.maximum(lowerCamelCase , log_spec.max() - 8.0 ) __snake_case : Union[str, Any] = (log_spec + 4.0) / 4.0 return log_spec @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def __snake_case ( lowerCamelCase : List[np.ndarray] , lowerCamelCase : List[np.ndarray] , lowerCamelCase : float = 0.0 ) -> List[np.ndarray]: if attention_mask is not None: __snake_case : List[str] = np.array(lowerCamelCase , np.intaa ) __snake_case : int = [] for vector, length in zip(lowerCamelCase , attention_mask.sum(-1 ) ): __snake_case : int = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: __snake_case : int = padding_value normed_input_values.append(lowerCamelCase ) else: __snake_case : List[str] = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def __call__( self : Any , lowerCamelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , lowerCamelCase : bool = True , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[str] = "max_length" , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[bool] = None , **lowerCamelCase : Optional[Any] , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( F'The model corresponding to this feature extractor: {self.__class__.__name__} was trained using a' F' sampling rate of {self.sampling_rate}. Please make sure that the provided `raw_speech` input' F' was sampled with {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( "It is strongly recommended to pass the `sampling_rate` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) __snake_case : Any = isinstance(lowerCamelCase , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(F'Only mono-channel audio is supported for input to {self}' ) __snake_case : Union[str, Any] = is_batched_numpy or ( isinstance(lowerCamelCase , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __snake_case : Any = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(lowerCamelCase , np.ndarray ): __snake_case : Tuple = np.asarray(lowerCamelCase , dtype=np.floataa ) elif isinstance(lowerCamelCase , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __snake_case : Dict = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __snake_case : List[Any] = [np.asarray([raw_speech] ).T] __snake_case : List[str] = BatchFeature({"input_features": raw_speech} ) # convert into correct format for padding __snake_case : Union[str, Any] = self.pad( lowerCamelCase , padding=lowerCamelCase , max_length=max_length if max_length else self.n_samples , truncation=lowerCamelCase , pad_to_multiple_of=lowerCamelCase , return_attention_mask=return_attention_mask or do_normalize , ) # zero-mean and unit-variance normalization if do_normalize: __snake_case : List[str] = self.zero_mean_unit_var_norm( padded_inputs["input_features"] , attention_mask=padded_inputs["attention_mask"] , padding_value=self.padding_value , ) __snake_case : Optional[int] = np.stack(padded_inputs["input_features"] , axis=0 ) # make sure list is in array format __snake_case : Optional[int] = padded_inputs.get("input_features" ).transpose(2 , 0 , 1 ) __snake_case : Tuple = [self._np_extract_fbank_features(lowerCamelCase ) for waveform in input_features[0]] if isinstance(input_features[0] , lowerCamelCase ): __snake_case : Dict = [np.asarray(lowerCamelCase , dtype=np.floataa ) for feature in input_features] else: __snake_case : Any = input_features if return_attention_mask: # rescale from sample (48000) to feature (3000) __snake_case : Tuple = padded_inputs["attention_mask"][:, :: self.hop_length] if return_tensors is not None: __snake_case : Dict = padded_inputs.convert_to_tensors(lowerCamelCase ) return padded_inputs def __snake_case ( self : str ) -> Dict[str, Any]: __snake_case : Tuple = copy.deepcopy(self.__dict__ ) __snake_case : str = self.__class__.__name__ if "mel_filters" in output: del output["mel_filters"] return output
81
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _snake_case : List[Any] = "\\n Text data.\n Second line of data." _snake_case : Tuple = "file" @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") __snake_case : Optional[Any] = bytes(__lowerCamelCase , "utf-8" ) with zstd.open(__lowerCamelCase , "wb" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture def lowerCAmelCase_ ( __lowerCamelCase ): with open(os.path.join(tmpfs.local_root_dir , __lowerCamelCase ) , "w" ) as f: f.write(__lowerCamelCase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} __snake_case : str = input_paths[compression_format] __snake_case : Optional[Any] = tmp_path / "cache" __snake_case : Optional[int] = DownloadConfig(cache_dir=__lowerCamelCase , extract_compressed_file=__lowerCamelCase ) __snake_case : Union[str, Any] = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) with open(__lowerCamelCase ) as f: __snake_case : Dict = f.read() with open(__lowerCamelCase ) as f: __snake_case : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = "custom_cache" __snake_case : List[str] = "custom_extracted_dir" __snake_case : Any = tmp_path / "custom_extracted_path" if default_extracted: __snake_case : List[Any] = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __lowerCamelCase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__lowerCamelCase ) ) __snake_case : Optional[Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __snake_case : Optional[int] = xz_file __snake_case : Optional[int] = ( DownloadConfig(extract_compressed_file=__lowerCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__lowerCamelCase ) ) __snake_case : str = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) assert Path(__lowerCamelCase ).parent.parts[-2:] == expected def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : Optional[Any] = str(Path(__lowerCamelCase ).resolve() ) assert cached_path(__lowerCamelCase ) == text_file # relative path __snake_case : Any = str(Path(__lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(__lowerCamelCase ) == text_file def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) # relative path __snake_case : Optional[int] = "./__missing_file__.txt" with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : str = get_from_cache(F'tmp://{tmpfs_file}' ) with open(__lowerCamelCase ) as f: __snake_case : Union[str, Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( ): with pytest.raises(__lowerCamelCase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): http_get("https://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[str] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): ftp_get("ftp://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): fsspec_get("s3://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): fsspec_head("s3://huggingface.co" )
81
1
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , lowerCamelCase : NestedDataStructureLike[PathLike] , lowerCamelCase : Optional[NamedSplit] = None , lowerCamelCase : Optional[Features] = None , lowerCamelCase : str = None , lowerCamelCase : bool = False , lowerCamelCase : bool = False , lowerCamelCase : Optional[int] = None , **lowerCamelCase : Any , ) -> Optional[Any]: super().__init__( lowerCamelCase , split=lowerCamelCase , features=lowerCamelCase , cache_dir=lowerCamelCase , keep_in_memory=lowerCamelCase , streaming=lowerCamelCase , num_proc=lowerCamelCase , **lowerCamelCase , ) __snake_case : int = path_or_paths if isinstance(lowerCamelCase , lowerCamelCase ) else {self.split: path_or_paths} __snake_case : List[Any] = Text( cache_dir=lowerCamelCase , data_files=lowerCamelCase , features=lowerCamelCase , **lowerCamelCase , ) def __snake_case ( self : str ) -> Tuple: # Build iterable dataset if self.streaming: __snake_case : str = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __snake_case : str = None __snake_case : List[Any] = None __snake_case : Any = None __snake_case : List[Any] = None self.builder.download_and_prepare( download_config=lowerCamelCase , download_mode=lowerCamelCase , verification_mode=lowerCamelCase , base_path=lowerCamelCase , num_proc=self.num_proc , ) __snake_case : Any = self.builder.as_dataset( split=self.split , verification_mode=lowerCamelCase , in_memory=self.keep_in_memory ) return dataset
81
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = start # add current to visited visited.append(__lowerCamelCase ) __snake_case : List[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __snake_case : Tuple = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # if all neighbors visited add current to sort sort.append(__lowerCamelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCamelCase ) != len(__lowerCamelCase ): for vertice in vertices: if vertice not in visited: __snake_case : int = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # return sort return sort if __name__ == "__main__": _snake_case : List[Any] = topological_sort("a", [], []) print(sort)
81
1
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = StableDiffusionSAGPipeline __UpperCAmelCase : List[str] = TEXT_TO_IMAGE_PARAMS __UpperCAmelCase : Dict = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCAmelCase : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase : Optional[Any] = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase : List[str] = False def __snake_case ( self : List[Any] ) -> List[str]: torch.manual_seed(0 ) __snake_case : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) __snake_case : Optional[int] = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=lowerCamelCase , set_alpha_to_one=lowerCamelCase , ) torch.manual_seed(0 ) __snake_case : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) __snake_case : Optional[Any] = CLIPTextModel(lowerCamelCase ) __snake_case : List[str] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) __snake_case : Dict = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def __snake_case ( self : Tuple , lowerCamelCase : List[Any] , lowerCamelCase : Union[str, Any]=0 ) -> List[Any]: if str(lowerCamelCase ).startswith("mps" ): __snake_case : Dict = torch.manual_seed(lowerCamelCase ) else: __snake_case : Optional[Any] = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) __snake_case : int = { "prompt": ".", "generator": generator, "num_inference_steps": 2, "guidance_scale": 1.0, "sag_scale": 1.0, "output_type": "numpy", } return inputs def __snake_case ( self : int ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> Union[str, Any]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Tuple = StableDiffusionSAGPipeline.from_pretrained("CompVis/stable-diffusion-v1-4" ) __snake_case : Tuple = sag_pipe.to(lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : int = "." __snake_case : int = torch.manual_seed(0 ) __snake_case : int = sag_pipe( [prompt] , generator=lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" ) __snake_case : int = output.images __snake_case : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __snake_case : List[Any] = np.array([0.15_68, 0.17_38, 0.16_95, 0.16_93, 0.15_07, 0.17_05, 0.15_47, 0.17_51, 0.19_49] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-2 def __snake_case ( self : str ) -> Dict: __snake_case : Optional[Any] = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) __snake_case : Tuple = sag_pipe.to(lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : Optional[Any] = "." __snake_case : List[str] = torch.manual_seed(0 ) __snake_case : str = sag_pipe( [prompt] , generator=lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" ) __snake_case : Tuple = output.images __snake_case : Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __snake_case : str = np.array([0.34_59, 0.28_76, 0.25_37, 0.30_02, 0.26_71, 0.21_60, 0.30_26, 0.22_62, 0.23_71] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-2 def __snake_case ( self : Tuple ) -> List[str]: __snake_case : str = StableDiffusionSAGPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base" ) __snake_case : List[Any] = sag_pipe.to(lowerCamelCase ) sag_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : int = "." __snake_case : Union[str, Any] = torch.manual_seed(0 ) __snake_case : Any = sag_pipe( [prompt] , width=768 , height=512 , generator=lowerCamelCase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="np" , ) __snake_case : Tuple = output.images assert image.shape == (1, 512, 768, 3)
81
def lowerCAmelCase_ ( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(__lowerCamelCase , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
81
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _snake_case : Optional[int] = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : List[str] = XGLMTokenizer __UpperCAmelCase : Union[str, Any] = XGLMTokenizerFast __UpperCAmelCase : List[Any] = True __UpperCAmelCase : Optional[Any] = True def __snake_case ( self : str ) -> int: super().setUp() # We have a SentencePiece fixture for testing __snake_case : Optional[int] = XGLMTokenizer(lowerCamelCase , keep_accents=lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : Optional[int] = "<pad>" __snake_case : Optional[int] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase ) , lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int ) -> Any: __snake_case : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(len(lowerCamelCase ) , 1008 ) def __snake_case ( self : str ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 1008 ) def __snake_case ( self : Optional[int] ) -> Any: __snake_case : Any = XGLMTokenizer(lowerCamelCase , keep_accents=lowerCamelCase ) __snake_case : Dict = tokenizer.tokenize("This is a test" ) self.assertListEqual(lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) __snake_case : Dict = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) __snake_case : Any = tokenizer.convert_tokens_to_ids(lowerCamelCase ) self.assertListEqual( lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) __snake_case : Dict = tokenizer.convert_ids_to_tokens(lowerCamelCase ) self.assertListEqual( lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def __snake_case ( self : List[Any] ) -> Optional[int]: return XGLMTokenizer.from_pretrained("facebook/xglm-564M" ) def __snake_case ( self : Optional[int] ) -> Optional[Any]: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(lowerCamelCase , f.name ) __snake_case : int = XGLMTokenizer(f.name , keep_accents=lowerCamelCase ) __snake_case : List[str] = pickle.dumps(lowerCamelCase ) pickle.loads(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> List[str]: if not self.test_rust_tokenizer: return __snake_case : Any = self.get_tokenizer() __snake_case : List[str] = self.get_rust_tokenizer() __snake_case : Optional[Any] = "I was born in 92000, and this is falsé." __snake_case : Optional[int] = tokenizer.tokenize(lowerCamelCase ) __snake_case : List[str] = rust_tokenizer.tokenize(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) __snake_case : List[Any] = tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) __snake_case : Any = rust_tokenizer.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) __snake_case : int = self.get_rust_tokenizer() __snake_case : Optional[int] = tokenizer.encode(lowerCamelCase ) __snake_case : List[Any] = rust_tokenizer.encode(lowerCamelCase ) self.assertListEqual(lowerCamelCase , lowerCamelCase ) @slow def __snake_case ( self : Optional[Any] ) -> List[str]: __snake_case : List[str] = "Hello World!" __snake_case : str = [2, 31227, 4447, 35] self.assertListEqual(lowerCamelCase , self.big_tokenizer.encode(lowerCamelCase ) ) @slow def __snake_case ( self : Any ) -> List[Any]: __snake_case : Optional[int] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off __snake_case : Any = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(lowerCamelCase , self.big_tokenizer.encode(lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> int: # fmt: off __snake_case : List[str] = { "input_ids": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase , model_name="facebook/xglm-564M" , padding=lowerCamelCase , )
81
from math import sqrt def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0_0_0 ): __snake_case : int = 0 __snake_case : int = 0 __snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__lowerCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
81
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Tuple = "char" __UpperCAmelCase : List[Any] = "bpe" __UpperCAmelCase : str = "wp" _snake_case : List[Any] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : str = ["image_processor", "char_tokenizer"] __UpperCAmelCase : Tuple = "ViTImageProcessor" __UpperCAmelCase : Tuple = "MgpstrTokenizer" def __init__( self : Any , lowerCamelCase : Tuple=None , lowerCamelCase : Optional[int]=None , **lowerCamelCase : List[str] ) -> Tuple: __snake_case : str = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , lowerCamelCase , ) __snake_case : int = kwargs.pop("feature_extractor" ) __snake_case : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) __snake_case : List[str] = tokenizer __snake_case : Optional[Any] = AutoTokenizer.from_pretrained("gpt2" ) __snake_case : Union[str, Any] = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(lowerCamelCase , lowerCamelCase ) def __call__( self : List[Any] , lowerCamelCase : List[str]=None , lowerCamelCase : Any=None , lowerCamelCase : Optional[int]=None , **lowerCamelCase : Any ) -> List[Any]: if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: __snake_case : str = self.image_processor(lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase ) if text is not None: __snake_case : Tuple = self.char_tokenizer(lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase ) if text is None: return inputs elif images is None: return encodings else: __snake_case : Dict = encodings["input_ids"] return inputs def __snake_case ( self : List[str] , lowerCamelCase : str ) -> Dict: __snake_case , __snake_case , __snake_case : Tuple = sequences __snake_case : List[str] = char_preds.size(0 ) __snake_case , __snake_case : Optional[Any] = self._decode_helper(lowerCamelCase , "char" ) __snake_case , __snake_case : Tuple = self._decode_helper(lowerCamelCase , "bpe" ) __snake_case , __snake_case : Optional[int] = self._decode_helper(lowerCamelCase , "wp" ) __snake_case : Tuple = [] __snake_case : Union[str, Any] = [] for i in range(lowerCamelCase ): __snake_case : List[str] = [char_scores[i], bpe_scores[i], wp_scores[i]] __snake_case : Optional[Any] = [char_strs[i], bpe_strs[i], wp_strs[i]] __snake_case : List[str] = scores.index(max(lowerCamelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __snake_case : Union[str, Any] = {} __snake_case : List[Any] = final_strs __snake_case : Union[str, Any] = final_scores __snake_case : Any = char_strs __snake_case : List[str] = bpe_strs __snake_case : Union[str, Any] = wp_strs return out def __snake_case ( self : Any , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> List[Any]: if format == DecodeType.CHARACTER: __snake_case : Optional[Any] = self.char_decode __snake_case : Union[str, Any] = 1 __snake_case : Tuple = "[s]" elif format == DecodeType.BPE: __snake_case : int = self.bpe_decode __snake_case : int = 2 __snake_case : List[str] = "#" elif format == DecodeType.WORDPIECE: __snake_case : int = self.wp_decode __snake_case : Tuple = 102 __snake_case : str = "[SEP]" else: raise ValueError(F'Format {format} is not supported.' ) __snake_case , __snake_case : Dict = [], [] __snake_case : Dict = pred_logits.size(0 ) __snake_case : str = pred_logits.size(1 ) __snake_case , __snake_case : Any = pred_logits.topk(1 , dim=-1 , largest=lowerCamelCase , sorted=lowerCamelCase ) __snake_case : Any = preds_index.view(-1 , lowerCamelCase )[:, 1:] __snake_case : str = decoder(lowerCamelCase ) __snake_case , __snake_case : List[Any] = torch.nn.functional.softmax(lowerCamelCase , dim=2 ).max(dim=2 ) __snake_case : Tuple = preds_max_prob[:, 1:] for index in range(lowerCamelCase ): __snake_case : int = preds_str[index].find(lowerCamelCase ) __snake_case : str = preds_str[index][:pred_eos] __snake_case : List[Any] = preds_index[index].cpu().tolist() __snake_case : Union[str, Any] = pred_index.index(lowerCamelCase ) if eos_token in pred_index else -1 __snake_case : Any = preds_max_prob[index][: pred_eos_index + 1] __snake_case : Dict = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(lowerCamelCase ) conf_scores.append(lowerCamelCase ) return dec_strs, conf_scores def __snake_case ( self : str , lowerCamelCase : Union[str, Any] ) -> Union[str, Any]: __snake_case : Optional[Any] = [seq.replace(" " , "" ) for seq in self.char_tokenizer.batch_decode(lowerCamelCase )] return decode_strs def __snake_case ( self : List[str] , lowerCamelCase : Tuple ) -> List[str]: return self.bpe_tokenizer.batch_decode(lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] ) -> int: __snake_case : List[str] = [seq.replace(" " , "" ) for seq in self.wp_tokenizer.batch_decode(lowerCamelCase )] return decode_strs
81
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : str ) -> str: __snake_case : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "neck_hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) ) class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Tuple=13 , lowerCamelCase : str=32 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=3 , lowerCamelCase : Any=640 , lowerCamelCase : Optional[Any]=4 , lowerCamelCase : Tuple="silu" , lowerCamelCase : int=3 , lowerCamelCase : Dict=32 , lowerCamelCase : str=0.1 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=0.02 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=10 , lowerCamelCase : int=None , ) -> str: __snake_case : Optional[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Any = image_size __snake_case : List[Any] = patch_size __snake_case : Any = num_channels __snake_case : Union[str, Any] = last_hidden_size __snake_case : Any = num_attention_heads __snake_case : Any = hidden_act __snake_case : Tuple = conv_kernel_size __snake_case : Any = output_stride __snake_case : Any = hidden_dropout_prob __snake_case : List[Any] = attention_probs_dropout_prob __snake_case : Optional[Any] = classifier_dropout_prob __snake_case : Union[str, Any] = use_labels __snake_case : Optional[int] = is_training __snake_case : Dict = num_labels __snake_case : Any = initializer_range __snake_case : Optional[int] = scope def __snake_case ( self : str ) -> Union[str, Any]: __snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : List[Any] = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __snake_case : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case ( self : Any ) -> Union[str, Any]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] ) -> Dict: __snake_case : List[Any] = MobileViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[str] = model(lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ) -> List[str]: __snake_case : str = self.num_labels __snake_case : List[Any] = MobileViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Dict: __snake_case : Union[str, Any] = self.num_labels __snake_case : Optional[int] = MobileViTForSemanticSegmentation(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Tuple = model(lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[int] ) -> List[Any]: __snake_case : Optional[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = config_and_inputs __snake_case : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Optional[Any] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Optional[int] = False def __snake_case ( self : Optional[int] ) -> Dict: __snake_case : Tuple = MobileViTModelTester(self ) __snake_case : Any = MobileViTConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds" ) def __snake_case ( self : Dict ) -> Any: pass @unittest.skip(reason="MobileViT does not support input and output embeddings" ) def __snake_case ( self : Dict ) -> List[Any]: pass @unittest.skip(reason="MobileViT does not output attentions" ) def __snake_case ( self : int ) -> Dict: pass def __snake_case ( self : int ) -> Union[str, Any]: __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = model_class(lowerCamelCase ) __snake_case : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __snake_case ( self : int ) -> Tuple: pass def __snake_case ( self : Any ) -> Tuple: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : Any ) -> str: def check_hidden_states_output(lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any ): __snake_case : int = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __snake_case : int = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __snake_case : Union[str, Any] = outputs.hidden_states __snake_case : int = 5 self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __snake_case : List[Any] = 2 for i in range(len(lowerCamelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __snake_case , __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : List[Any] = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Any ) -> Any: __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> List[str]: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase ) @slow def __snake_case ( self : List[str] ) -> Any: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = MobileViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def lowerCAmelCase_ ( ): __snake_case : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a (unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : str ) -> Dict: return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None @slow def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : Tuple = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowerCamelCase ) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Dict = model(**lowerCamelCase ) # verify the logits __snake_case : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : str ) -> Optional[int]: __snake_case : Optional[int] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : str = model.to(lowerCamelCase ) __snake_case : int = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Optional[int] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : List[str] = model(**lowerCamelCase ) __snake_case : Union[str, Any] = outputs.logits # verify the logits __snake_case : Tuple = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , lowerCamelCase ) __snake_case : Union[str, Any] = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ] , device=lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : Union[str, Any] ) -> Optional[int]: __snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Tuple = model.to(lowerCamelCase ) __snake_case : Dict = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Any = model(**lowerCamelCase ) __snake_case : Dict = outputs.logits.detach().cpu() __snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(50, 60)] ) __snake_case : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , lowerCamelCase ) __snake_case : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ) __snake_case : Optional[int] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , lowerCamelCase )
81
1
import os import sys import unittest _snake_case : Any = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path _snake_case : Optional[Any] = os.path.join(git_repo_path, "src", "transformers") _snake_case : int = "\n{0} = None\n" _snake_case : Dict = "\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n" _snake_case : Tuple = "\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n" class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Dict ) -> Optional[int]: __snake_case : str = find_backend(" _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")" ) self.assertIsNone(lowerCamelCase ) __snake_case : str = find_backend(" if not is_tokenizers_available():" ) self.assertEqual(lowerCamelCase , "tokenizers" ) __snake_case : List[str] = find_backend(" if not is_tensorflow_text_available():" ) self.assertEqual(lowerCamelCase , "tensorflow_text" ) __snake_case : Any = find_backend(" if not (is_sentencepiece_available() and is_tokenizers_available()):" ) self.assertEqual(lowerCamelCase , "sentencepiece_and_tokenizers" ) __snake_case : List[Any] = find_backend( " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" ) self.assertEqual(lowerCamelCase , "sentencepiece_and_tensorflow_text" ) __snake_case : Union[str, Any] = find_backend( " if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):" ) self.assertEqual(lowerCamelCase , "sentencepiece_and_tokenizers_and_vision" ) def __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case : List[Any] = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("torch" , lowerCamelCase ) self.assertIn("tensorflow_text" , lowerCamelCase ) self.assertIn("sentencepiece_and_tokenizers" , lowerCamelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn("BertModel" , objects["torch"] ) self.assertIn("TFBertModel" , objects["tf"] ) self.assertIn("FlaxBertModel" , objects["flax"] ) self.assertIn("BertModel" , objects["torch"] ) self.assertIn("TFBertTokenizer" , objects["tensorflow_text"] ) self.assertIn("convert_slow_tokenizer" , objects["sentencepiece_and_tokenizers"] ) def __snake_case ( self : Dict ) -> Union[str, Any]: __snake_case : int = create_dummy_object("CONSTANT" , "'torch'" ) self.assertEqual(lowerCamelCase , "\nCONSTANT = None\n" ) __snake_case : Tuple = create_dummy_object("function" , "'torch'" ) self.assertEqual( lowerCamelCase , "\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n" ) __snake_case : Optional[Any] = "\nclass FakeClass(metaclass=DummyObject):\n _backends = 'torch'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, 'torch')\n" __snake_case : List[Any] = create_dummy_object("FakeClass" , "'torch'" ) self.assertEqual(lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> Optional[Any]: __snake_case : Optional[int] = "# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, [\"torch\"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = [\"torch\"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, [\"torch\"])\n" __snake_case : Any = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]} ) self.assertEqual(dummy_files["torch"] , lowerCamelCase )
81
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _snake_case : int = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : List[Any] , **lowerCamelCase : int ) -> None: warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
1
import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class a : """simple docstring""" def __init__( self : Any , lowerCamelCase : str , lowerCamelCase : Optional[Any]=2 , lowerCamelCase : Dict=True , lowerCamelCase : Dict=False , lowerCamelCase : Optional[Any]=10 , lowerCamelCase : Tuple=3 , lowerCamelCase : List[Any]=32 * 8 , lowerCamelCase : Dict=32 * 8 , lowerCamelCase : int=4 , lowerCamelCase : Tuple=64 , ) -> Tuple: __snake_case : List[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Any = is_training __snake_case : Dict = use_auxiliary_loss __snake_case : Union[str, Any] = num_queries __snake_case : Union[str, Any] = num_channels __snake_case : Dict = min_size __snake_case : Any = max_size __snake_case : Any = num_labels __snake_case : Tuple = hidden_dim __snake_case : Optional[Any] = hidden_dim def __snake_case ( self : List[Any] ) -> str: __snake_case : int = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( lowerCamelCase ) __snake_case : Tuple = torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowerCamelCase ) __snake_case : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowerCamelCase ) > 0.5 ).float() __snake_case : List[str] = (torch.rand((self.batch_size, self.num_labels) , device=lowerCamelCase ) > 0.5).long() __snake_case : int = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def __snake_case ( self : int ) -> Tuple: __snake_case : str = MaskaFormerConfig( hidden_size=self.hidden_dim , ) __snake_case : int = self.num_queries __snake_case : Optional[Any] = self.num_labels __snake_case : List[str] = [1, 1, 1, 1] __snake_case : Optional[int] = self.num_channels __snake_case : str = 64 __snake_case : Tuple = 128 __snake_case : Optional[int] = self.hidden_dim __snake_case : List[str] = self.hidden_dim __snake_case : List[Any] = self.hidden_dim return config def __snake_case ( self : Optional[int] ) -> Optional[Any]: __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : Optional[int] = self.prepare_config_and_inputs() __snake_case : Union[str, Any] = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def __snake_case ( self : Optional[Any] , lowerCamelCase : Tuple , lowerCamelCase : int ) -> int: __snake_case : Dict = output.encoder_hidden_states __snake_case : List[str] = output.pixel_decoder_hidden_states __snake_case : List[Any] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowerCamelCase ) , config.decoder_layers ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : Union[str, Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Union[str, Any]=False ) -> Any: with torch.no_grad(): __snake_case : Any = MaskaFormerModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : int = model(pixel_values=lowerCamelCase , pixel_mask=lowerCamelCase ) __snake_case : List[str] = model(lowerCamelCase , output_hidden_states=lowerCamelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.hidden_dim) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Optional[int] , lowerCamelCase : int , lowerCamelCase : Any , lowerCamelCase : str , lowerCamelCase : List[Any] , lowerCamelCase : Any ) -> Any: __snake_case : Tuple = MaskaFormerForUniversalSegmentation(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() def comm_check_on_output(lowerCamelCase : Union[str, Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __snake_case : int = model(pixel_values=lowerCamelCase , pixel_mask=lowerCamelCase ) __snake_case : int = model(lowerCamelCase ) comm_check_on_output(lowerCamelCase ) __snake_case : Optional[int] = model( pixel_values=lowerCamelCase , pixel_mask=lowerCamelCase , mask_labels=lowerCamelCase , class_labels=lowerCamelCase ) comm_check_on_output(lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Union[str, Any] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () __UpperCAmelCase : int = {"feature-extraction": MaskaFormerModel} if is_torch_available() else {} __UpperCAmelCase : Tuple = False __UpperCAmelCase : Dict = False __UpperCAmelCase : List[Any] = False __UpperCAmelCase : Union[str, Any] = False def __snake_case ( self : List[Any] ) -> Dict: __snake_case : List[str] = MaskaFormerModelTester(self ) __snake_case : Optional[int] = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def __snake_case ( self : int ) -> Any: self.config_tester.run_common_tests() def __snake_case ( self : Tuple ) -> List[Any]: __snake_case , __snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowerCamelCase , **lowerCamelCase , output_hidden_states=lowerCamelCase ) def __snake_case ( self : Dict ) -> Tuple: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowerCamelCase ) @unittest.skip(reason="Mask2Former does not use inputs_embeds" ) def __snake_case ( self : List[Any] ) -> Any: pass @unittest.skip(reason="Mask2Former does not have a get_input_embeddings method" ) def __snake_case ( self : int ) -> Union[str, Any]: pass @unittest.skip(reason="Mask2Former is not a generative model" ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: pass @unittest.skip(reason="Mask2Former does not use token embeddings" ) def __snake_case ( self : Dict ) -> str: pass @require_torch_multi_gpu @unittest.skip( reason="Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def __snake_case ( self : List[str] ) -> Union[str, Any]: pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __snake_case ( self : Union[str, Any] ) -> int: pass def __snake_case ( self : Any ) -> Any: __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[Any] = model_class(lowerCamelCase ) __snake_case : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : List[Any] = [*signature.parameters.keys()] __snake_case : str = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) @slow def __snake_case ( self : str ) -> List[str]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: __snake_case : Optional[int] = MaskaFormerModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def __snake_case ( self : int ) -> List[Any]: __snake_case : int = (self.model_tester.min_size,) * 2 __snake_case : Optional[int] = { "pixel_values": torch.randn((2, 3, *size) , device=lowerCamelCase ), "mask_labels": torch.randn((2, 10, *size) , device=lowerCamelCase ), "class_labels": torch.zeros(2 , 10 , device=lowerCamelCase ).long(), } __snake_case : Tuple = self.model_tester.get_config() __snake_case : Optional[Any] = MaskaFormerForUniversalSegmentation(lowerCamelCase ).to(lowerCamelCase ) __snake_case : str = model(**lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def __snake_case ( self : Any ) -> List[str]: __snake_case , __snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(lowerCamelCase , **lowerCamelCase , output_hidden_states=lowerCamelCase ) def __snake_case ( self : List[str] ) -> Union[str, Any]: __snake_case , __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : List[str] = model_class(lowerCamelCase ).to(lowerCamelCase ) __snake_case : Dict = model(**lowerCamelCase , output_attentions=lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def __snake_case ( self : int ) -> Dict: if not self.model_tester.is_training: return __snake_case : Union[str, Any] = self.all_model_classes[1] __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() __snake_case : int = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.train() __snake_case : int = model(lowerCamelCase , mask_labels=lowerCamelCase , class_labels=lowerCamelCase ).loss loss.backward() def __snake_case ( self : Optional[Any] ) -> str: __snake_case : Tuple = self.all_model_classes[1] __snake_case , __snake_case , __snake_case , __snake_case , __snake_case : int = self.model_tester.prepare_config_and_inputs() __snake_case : Optional[Any] = True __snake_case : int = True __snake_case : int = model_class(lowerCamelCase ).to(lowerCamelCase ) model.train() __snake_case : Optional[int] = model(lowerCamelCase , mask_labels=lowerCamelCase , class_labels=lowerCamelCase ) __snake_case : str = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __snake_case : Tuple = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() __snake_case : int = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __snake_case : Optional[Any] = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _snake_case : List[str] = 1E-4 def lowerCAmelCase_ ( ): __snake_case : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class a (unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : Union[str, Any] ) -> Union[str, Any]: return "facebook/mask2former-swin-small-coco-instance" @cached_property def __snake_case ( self : Tuple ) -> int: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def __snake_case ( self : Tuple ) -> Optional[int]: __snake_case : int = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(lowerCamelCase ) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Tuple = prepare_img() __snake_case : Dict = image_processor(lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) __snake_case : List[str] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): __snake_case : str = model(**lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor( [[-0.27_90, -1.07_17, -1.16_68], [-0.51_28, -0.31_28, -0.49_87], [-0.58_32, 0.19_71, -0.01_97]] ).to(lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase , atol=lowerCamelCase ) ) __snake_case : Tuple = torch.tensor( [[0.89_73, 1.18_47, 1.17_76], [1.19_34, 1.50_40, 1.51_28], [1.11_53, 1.44_86, 1.49_51]] ).to(lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowerCamelCase , atol=lowerCamelCase ) ) __snake_case : List[str] = torch.tensor( [[2.11_52, 1.70_00, -0.86_03], [1.58_08, 1.80_04, -0.93_53], [1.60_43, 1.74_95, -0.59_99]] ).to(lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowerCamelCase , atol=lowerCamelCase ) ) def __snake_case ( self : int ) -> Tuple: __snake_case : Union[str, Any] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase ).eval() __snake_case : Optional[int] = self.default_image_processor __snake_case : str = prepare_img() __snake_case : int = image_processor(lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) __snake_case : List[Any] = inputs["pixel_values"].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowerCamelCase , (1, 3, 384, 384) ) with torch.no_grad(): __snake_case : Any = model(**lowerCamelCase ) # masks_queries_logits __snake_case : Optional[Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) __snake_case : Optional[int] = [ [-8.78_39, -9.00_56, -8.81_21], [-7.41_04, -7.03_13, -6.54_01], [-6.61_05, -6.34_27, -6.46_75], ] __snake_case : Any = torch.tensor(lowerCamelCase ).to(lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowerCamelCase , atol=lowerCamelCase ) ) # class_queries_logits __snake_case : Tuple = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape , (1, model.config.num_queries, model.config.num_labels + 1) ) __snake_case : Optional[Any] = torch.tensor( [ [1.83_24, -8.08_35, -4.19_22], [0.84_50, -9.00_50, -3.60_53], [0.30_45, -7.72_93, -3.02_75], ] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowerCamelCase , atol=lowerCamelCase ) ) def __snake_case ( self : int ) -> List[str]: __snake_case : Optional[int] = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(lowerCamelCase ).eval() __snake_case : List[str] = self.default_image_processor __snake_case : Optional[Any] = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) __snake_case : Tuple = inputs["pixel_values"].to(lowerCamelCase ) __snake_case : List[str] = [el.to(lowerCamelCase ) for el in inputs["mask_labels"]] __snake_case : Tuple = [el.to(lowerCamelCase ) for el in inputs["class_labels"]] with torch.no_grad(): __snake_case : Dict = model(**lowerCamelCase ) self.assertTrue(outputs.loss is not None )
81
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 _snake_case : Optional[Any] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[str] = ["pixel_values"] def __init__( self : List[Any] , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : int = 8 , **lowerCamelCase : Tuple , ) -> None: super().__init__(**lowerCamelCase ) __snake_case : Dict = do_rescale __snake_case : Dict = rescale_factor __snake_case : Optional[Any] = do_pad __snake_case : Tuple = pad_size def __snake_case ( self : Dict , lowerCamelCase : np.ndarray , lowerCamelCase : float , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Optional[int] ) -> np.ndarray: return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : int , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None ) -> Tuple: __snake_case , __snake_case : List[str] = get_image_size(lowerCamelCase ) __snake_case : Optional[Any] = (old_height // size + 1) * size - old_height __snake_case : List[Any] = (old_width // size + 1) * size - old_width return pad(lowerCamelCase , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCamelCase ) def __snake_case ( self : Tuple , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : Union[str, Any] , ) -> List[str]: __snake_case : int = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : str = do_pad if do_pad is not None else self.do_pad __snake_case : Any = pad_size if pad_size is not None else self.pad_size __snake_case : int = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __snake_case : str = [to_numpy_array(lowerCamelCase ) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_pad: __snake_case : Optional[Any] = [self.pad(lowerCamelCase , size=lowerCamelCase ) for image in images] __snake_case : int = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __snake_case : Union[str, Any] = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
81
1
class a : """simple docstring""" def __init__( self : List[str] ) -> List[str]: __snake_case : Dict = "" __snake_case : str = "" __snake_case : int = [] def __snake_case ( self : int , lowerCamelCase : int , lowerCamelCase : int ) -> int: if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: __snake_case : List[str] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: __snake_case : Tuple = self.__min_dist_top_down_dp(lowerCamelCase , n - 1 ) __snake_case : int = self.__min_dist_top_down_dp(m - 1 , lowerCamelCase ) __snake_case : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) __snake_case : int = 1 + min(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return self.dp[m][n] def __snake_case ( self : str , lowerCamelCase : str , lowerCamelCase : str ) -> int: __snake_case : Tuple = worda __snake_case : Any = worda __snake_case : Optional[int] = [[-1 for _ in range(len(lowerCamelCase ) )] for _ in range(len(lowerCamelCase ) )] return self.__min_dist_top_down_dp(len(lowerCamelCase ) - 1 , len(lowerCamelCase ) - 1 ) def __snake_case ( self : Optional[Any] , lowerCamelCase : str , lowerCamelCase : str ) -> int: __snake_case : List[Any] = worda __snake_case : Tuple = worda __snake_case : Dict = len(lowerCamelCase ) __snake_case : Union[str, Any] = len(lowerCamelCase ) __snake_case : Optional[int] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty __snake_case : Tuple = j elif j == 0: # second string is empty __snake_case : List[str] = i elif worda[i - 1] == worda[j - 1]: # last characters are equal __snake_case : Any = self.dp[i - 1][j - 1] else: __snake_case : Union[str, Any] = self.dp[i][j - 1] __snake_case : List[str] = self.dp[i - 1][j] __snake_case : int = self.dp[i - 1][j - 1] __snake_case : Optional[int] = 1 + min(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return self.dp[m][n] if __name__ == "__main__": _snake_case : Union[str, Any] = EditDistance() print("****************** Testing Edit Distance DP Algorithm ******************") print() _snake_case : Dict = input("Enter the first string: ").strip() _snake_case : Any = input("Enter the second string: ").strip() print() print(f'''The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}''') print(f'''The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}''') print() print("*************** End of Testing Edit Distance DP Algorithm ***************")
81
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Any = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
1
from __future__ import annotations def __lowercase ( snake_case ): """simple docstring""" __magic_name__ :int = len(snake_case ) # We need to create solution object to save path. __magic_name__ :List[str] = [[0 for _ in range(snake_case )] for _ in range(snake_case )] __magic_name__ :Dict = run_maze(snake_case, 0, 0, snake_case ) if solved: print('''\n'''.join(str(snake_case ) for row in solutions ) ) else: print('''No solution exists!''' ) return solved def __lowercase ( snake_case, snake_case, snake_case, snake_case ): """simple docstring""" __magic_name__ :Tuple = len(snake_case ) # Final check point. if i == j == (size - 1): __magic_name__ :Optional[int] = 1 return True __magic_name__ :Union[str, Any] = (not i < 0) and (not j < 0) # Check lower bounds __magic_name__ :Dict = (i < size) and (j < size) # Check upper bounds if lower_flag and upper_flag: # check for already visited and block points. __magic_name__ :int = (not solutions[i][j]) and (not maze[i][j]) if block_flag: # check visited __magic_name__ :Any = 1 # check for directions if ( run_maze(snake_case, i + 1, snake_case, snake_case ) or run_maze(snake_case, snake_case, j + 1, snake_case ) or run_maze(snake_case, i - 1, snake_case, snake_case ) or run_maze(snake_case, snake_case, j - 1, snake_case ) ): return True __magic_name__ :Optional[int] = 0 return False return False if __name__ == "__main__": import doctest doctest.testmod()
0
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging _snake_case : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : CLIPSegForImageSegmentation , lowerCamelCase : CLIPSegProcessor , lowerCamelCase : AutoencoderKL , lowerCamelCase : CLIPTextModel , lowerCamelCase : CLIPTokenizer , lowerCamelCase : UNetaDConditionModel , lowerCamelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCamelCase : StableDiffusionSafetyChecker , lowerCamelCase : CLIPImageProcessor , ) -> Tuple: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __snake_case : Tuple = ( F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : Any = dict(scheduler.config ) __snake_case : List[Any] = 1 __snake_case : Tuple = FrozenDict(lowerCamelCase ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __snake_case : List[str] = ( F'The configuration file of this scheduler: {scheduler} has not set the configuration' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : List[str] = dict(scheduler.config ) __snake_case : List[str] = True __snake_case : Any = FrozenDict(lowerCamelCase ) if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=lowerCamelCase , segmentation_processor=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , ) def __snake_case ( self : Dict , lowerCamelCase : Optional[Union[str, int]] = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Any: self.enable_attention_slicing(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> str: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __snake_case : Optional[int] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase , lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : int ) -> Any: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any] , lowerCamelCase : Union[str, List[str]] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : str , lowerCamelCase : int = 512 , lowerCamelCase : int = 512 , lowerCamelCase : int = 50 , lowerCamelCase : float = 7.5 , lowerCamelCase : Optional[Union[str, List[str]]] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : float = 0.0 , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : Optional[torch.FloatTensor] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase : int = 1 , **lowerCamelCase : Dict , ) -> List[str]: __snake_case : Tuple = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __snake_case : str = self.segmentation_model(**lowerCamelCase ) __snake_case : Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __snake_case : List[Any] = self.numpy_to_pil(lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __snake_case : Tuple = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=lowerCamelCase , image=lowerCamelCase , mask_image=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , )
81
0
from __future__ import annotations from functools import lru_cache from math import ceil __snake_case = 1_0_0 __snake_case = set(range(3, NUM_PRIMES, 2)) primes.add(2) __snake_case = 42 for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_00 ) def _A ( _lowercase ) -> set[int]: """simple docstring""" if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} __UpperCamelCase = set() __UpperCamelCase = 42 __UpperCamelCase = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def _A ( _lowercase = 50_00 ) -> int | None: """simple docstring""" for number_to_partition in range(1 , _lowercase ): if len(partition(_lowercase ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f"""{solution() = }""")
1
class a : """simple docstring""" def __init__( self : Tuple , lowerCamelCase : list ) -> None: __snake_case : str = set_counts __snake_case : Union[str, Any] = max(lowerCamelCase ) __snake_case : List[Any] = len(lowerCamelCase ) __snake_case : Tuple = [1] * num_sets __snake_case : Dict = list(range(lowerCamelCase ) ) def __snake_case ( self : str , lowerCamelCase : int , lowerCamelCase : int ) -> bool: __snake_case : List[Any] = self.get_parent(lowerCamelCase ) __snake_case : Tuple = self.get_parent(lowerCamelCase ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] __snake_case : List[str] = 0 __snake_case : List[Any] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __snake_case : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __snake_case : Union[str, Any] = 0 __snake_case : Optional[int] = src_parent __snake_case : Tuple = self.set_counts[src_parent] __snake_case : str = max(self.max_set , lowerCamelCase ) return True def __snake_case ( self : int , lowerCamelCase : int ) -> int: if self.parents[disj_set] == disj_set: return disj_set __snake_case : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
81
0
def SCREAMING_SNAKE_CASE_ ( _snake_case :list , _snake_case :list , _snake_case :int , _snake_case :int , _snake_case :int ) -> int: if index == number_of_items: return 0 _A = 0 _A = 0 _A = knapsack(_snake_case , _snake_case , _snake_case , _snake_case , index + 1 ) if weights[index] <= max_weight: _A = values[index] + knapsack( _snake_case , _snake_case , _snake_case , max_weight - weights[index] , index + 1 ) return max(_snake_case , _snake_case ) if __name__ == "__main__": import doctest doctest.testmod()
2
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : int , lowerCamelCase : Any , lowerCamelCase : int=7 , lowerCamelCase : str=3 , lowerCamelCase : Optional[int]=30 , lowerCamelCase : Dict=400 , lowerCamelCase : str=True , lowerCamelCase : str=None , lowerCamelCase : Any=True , lowerCamelCase : Union[str, Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[int]=1 / 255 , lowerCamelCase : Any=True , ) -> str: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __snake_case : Optional[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __snake_case : Optional[Any] = parent __snake_case : List[Any] = batch_size __snake_case : Optional[int] = num_channels __snake_case : str = min_resolution __snake_case : int = max_resolution __snake_case : int = do_resize __snake_case : Tuple = size __snake_case : Any = do_normalize __snake_case : int = image_mean __snake_case : Tuple = image_std __snake_case : Dict = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : str = do_pad def __snake_case ( self : Any ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __snake_case ( self : Dict , lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any]=False ) -> List[str]: if not batched: __snake_case : Dict = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : Dict = image.size else: __snake_case , __snake_case : List[str] = image.shape[1], image.shape[2] if w < h: __snake_case : Optional[int] = int(self.size["shortest_edge"] * h / w ) __snake_case : int = self.size["shortest_edge"] elif w > h: __snake_case : List[str] = self.size["shortest_edge"] __snake_case : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: __snake_case : List[Any] = self.size["shortest_edge"] __snake_case : Any = self.size["shortest_edge"] else: __snake_case : int = [] for image in image_inputs: __snake_case , __snake_case : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Optional[Any] = ConditionalDetrImageProcessingTester(self ) @property def __snake_case ( self : Any ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any] ) -> Optional[int]: __snake_case : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def __snake_case ( self : Any ) -> Dict: __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) __snake_case : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> Dict: pass def __snake_case ( self : Tuple ) -> str: # Initialize image_processing __snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __snake_case : Dict = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> str: # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : List[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> List[str]: # Initialize image_processing __snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : List[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : int = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __snake_case ( self : Any ) -> Optional[int]: # prepare image and target __snake_case : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : List[Any] = {"image_id": 39769, "annotations": target} # encode them __snake_case : List[str] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __snake_case : List[str] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Optional[int] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : List[Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Optional[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __snake_case : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Tuple = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> Tuple: # prepare image, target and masks_path __snake_case : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : str = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} __snake_case : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __snake_case : int = ConditionalDetrImageProcessor(format="coco_panoptic" ) __snake_case : str = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : Any = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : int = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __snake_case : List[Any] = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __snake_case : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
81
0
'''simple docstring''' import os import pytest from attr import dataclass lowerCAmelCase : Dict = 'us-east-1' # defaults region @dataclass class SCREAMING_SNAKE_CASE__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = """arn:aws:iam::558105141721:role/sagemaker_execution_role""" lowerCAmelCase_ = { """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""": 5_00, """save_steps""": 55_00, } lowerCAmelCase_ = {**hyperparameters, """max_steps""": 10_00} @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' 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 )-> str: '''simple docstring''' return F'''{self.framework}-transfromers-test''' @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' return F'''./tests/sagemaker/scripts/{self.framework}''' @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' 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 A_( A : Optional[int]): UpperCamelCase = SageMakerTestEnvironment(framework=request.cls.framework)
3
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _snake_case : Optional[Any] = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _snake_case : Dict = "UperNetConfig" class a (nn.Module ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : Union[int, Tuple[int, int]] , lowerCamelCase : Union[int, Tuple[int, int], str] = 0 , lowerCamelCase : bool = False , lowerCamelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() __snake_case : Union[str, Any] = nn.Convad( in_channels=lowerCamelCase , out_channels=lowerCamelCase , kernel_size=lowerCamelCase , padding=lowerCamelCase , bias=lowerCamelCase , dilation=lowerCamelCase , ) __snake_case : Dict = nn.BatchNormad(lowerCamelCase ) __snake_case : List[Any] = nn.ReLU() def __snake_case ( self : List[Any] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : Dict = self.conv(lowerCamelCase ) __snake_case : int = self.batch_norm(lowerCamelCase ) __snake_case : Optional[Any] = self.activation(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : str , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ) -> None: super().__init__() __snake_case : Tuple = [ nn.AdaptiveAvgPoolad(lowerCamelCase ), UperNetConvModule(lowerCamelCase , lowerCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : Dict , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : List[str] = input for layer in self.layers: __snake_case : Tuple = layer(lowerCamelCase ) return hidden_state class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple[int, ...] , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : bool ) -> None: super().__init__() __snake_case : Dict = pool_scales __snake_case : List[str] = align_corners __snake_case : List[Any] = in_channels __snake_case : str = channels __snake_case : Optional[Any] = [] for i, pool_scale in enumerate(lowerCamelCase ): __snake_case : Union[str, Any] = UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase , in_channels=lowerCamelCase , channels=lowerCamelCase ) self.blocks.append(lowerCamelCase ) self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> List[torch.Tensor]: __snake_case : Tuple = [] for ppm in self.blocks: __snake_case : Any = ppm(lowerCamelCase ) __snake_case : List[Any] = nn.functional.interpolate( lowerCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(lowerCamelCase ) return ppm_outs class a (nn.Module ): """simple docstring""" def __init__( self : int , lowerCamelCase : str , lowerCamelCase : str ) -> List[str]: super().__init__() __snake_case : Dict = config __snake_case : List[str] = config.pool_scales # e.g. (1, 2, 3, 6) __snake_case : Tuple = in_channels __snake_case : str = config.hidden_size __snake_case : List[str] = False __snake_case : Any = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __snake_case : Tuple = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __snake_case : List[str] = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __snake_case : List[Any] = nn.ModuleList() __snake_case : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __snake_case : Union[str, Any] = UperNetConvModule(lowerCamelCase , self.channels , kernel_size=1 ) __snake_case : Optional[int] = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(lowerCamelCase ) self.fpn_convs.append(lowerCamelCase ) __snake_case : int = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def __snake_case ( self : List[str] ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> str: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : List[Any] , lowerCamelCase : Tuple ) -> Optional[int]: __snake_case : str = inputs[-1] __snake_case : int = [x] psp_outs.extend(self.psp_modules(lowerCamelCase ) ) __snake_case : Tuple = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Union[str, Any] = self.bottleneck(lowerCamelCase ) return output def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # build laterals __snake_case : Any = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(lowerCamelCase ) ) # build top-down path __snake_case : Dict = len(lowerCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Union[str, Any] = laterals[i - 1].shape[2:] __snake_case : Optional[int] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=lowerCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs __snake_case : str = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Tuple = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) __snake_case : str = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Optional[Any] = self.fpn_bottleneck(lowerCamelCase ) __snake_case : Tuple = self.classifier(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int = 2 , lowerCamelCase : int = 3 , lowerCamelCase : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() __snake_case : List[Any] = config __snake_case : List[str] = config.auxiliary_in_channels __snake_case : List[Any] = config.auxiliary_channels __snake_case : Tuple = config.auxiliary_num_convs __snake_case : int = config.auxiliary_concat_input __snake_case : Optional[int] = in_index __snake_case : Tuple = (kernel_size // 2) * dilation __snake_case : Optional[int] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) if self.num_convs == 0: __snake_case : Union[str, Any] = nn.Identity() else: __snake_case : Any = nn.Sequential(*lowerCamelCase ) if self.concat_input: __snake_case : int = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=lowerCamelCase , padding=kernel_size // 2 ) __snake_case : Optional[Any] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def __snake_case ( self : Dict ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : Tuple ) -> Optional[int]: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : Optional[int] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps __snake_case : List[str] = encoder_hidden_states[self.in_index] __snake_case : Optional[Any] = self.convs(lowerCamelCase ) if self.concat_input: __snake_case : Optional[Any] = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __snake_case : Union[str, Any] = self.classifier(lowerCamelCase ) return output class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = UperNetConfig __UpperCAmelCase : int = "pixel_values" __UpperCAmelCase : str = True def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> List[Any]: if isinstance(lowerCamelCase , lowerCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def __snake_case ( self : Optional[Any] ) -> List[str]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def __snake_case ( self : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[Any]=False ) -> Dict: if isinstance(lowerCamelCase , lowerCamelCase ): __snake_case : Union[str, Any] = value _snake_case : Dict = R"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _snake_case : Tuple = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , _lowerCAmelCase , ) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Dict , lowerCamelCase : int ) -> Optional[int]: super().__init__(lowerCamelCase ) __snake_case : Any = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __snake_case : Union[str, Any] = UperNetHead(lowerCamelCase , in_channels=self.backbone.channels ) __snake_case : Any = UperNetFCNHead(lowerCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: __snake_case : Any = return_dict if return_dict is not None else self.config.use_return_dict __snake_case : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case : str = output_attentions if output_attentions is not None else self.config.output_attentions __snake_case : Tuple = self.backbone.forward_with_filtered_kwargs( lowerCamelCase , output_hidden_states=lowerCamelCase , output_attentions=lowerCamelCase ) __snake_case : List[Any] = outputs.feature_maps __snake_case : List[Any] = self.decode_head(lowerCamelCase ) __snake_case : List[str] = nn.functional.interpolate(lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : Optional[int] = None if self.auxiliary_head is not None: __snake_case : Dict = self.auxiliary_head(lowerCamelCase ) __snake_case : Dict = nn.functional.interpolate( lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : int = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss __snake_case : Any = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __snake_case : Union[str, Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __snake_case : Any = (logits,) + outputs[1:] else: __snake_case : str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
81
0
"""simple docstring""" __UpperCamelCase : int = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/''' def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : bytes ): # Make sure the supplied data is a bytes-like object if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCAmelCase = F'a bytes-like object is required, not \'{data.__class__.__name__}\'' raise TypeError(_UpperCAmelCase ) lowerCAmelCase = ''.join(bin(_UpperCAmelCase )[2:].zfill(8 ) for byte in data ) lowerCAmelCase = len(_UpperCAmelCase ) % 6 != 0 if padding_needed: # The padding that will be added later lowerCAmelCase = b'=' * ((6 - len(_UpperCAmelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_UpperCAmelCase ) % 6) else: lowerCAmelCase = b'' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(_UpperCAmelCase ) , 6 ) ).encode() + padding ) def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : str ): # Make sure encoded_data is either a string or a bytes-like object if not isinstance(_UpperCAmelCase , _UpperCAmelCase ) and not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCAmelCase = ( 'argument should be a bytes-like object or ASCII string, ' F'not \'{encoded_data.__class__.__name__}\'' ) raise TypeError(_UpperCAmelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_UpperCAmelCase , _UpperCAmelCase ): try: lowerCAmelCase = encoded_data.decode('utf-8' ) except UnicodeDecodeError: raise ValueError('base64 encoded data should only contain ASCII characters' ) lowerCAmelCase = encoded_data.count('=' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_UpperCAmelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowerCAmelCase = encoded_data[:-padding] lowerCAmelCase = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowerCAmelCase = ''.join( bin(B64_CHARSET.index(_UpperCAmelCase ) )[2:].zfill(6 ) for char in encoded_data ) lowerCAmelCase = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(_UpperCAmelCase ) , 8 ) ] return bytes(_UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
4
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase ): if not nums: return 0 __snake_case : Any = nums[0] __snake_case : str = 0 for num in nums[1:]: __snake_case , __snake_case : List[str] = ( max_excluding + num, max(__lowerCamelCase , __lowerCamelCase ), ) return max(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
81
0
'''simple docstring''' from __future__ import annotations def A (__lowerCamelCase :list[int] ): if not nums: return 0 _lowerCAmelCase = nums[0] _lowerCAmelCase = 0 for num in nums[1:]: _lowerCAmelCase , _lowerCAmelCase = ( max_excluding + num, max(__lowerCamelCase , __lowerCamelCase ), ) return max(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
5
from __future__ import annotations from typing import Any def lowerCAmelCase_ ( __lowerCamelCase ): create_state_space_tree(__lowerCamelCase , [] , 0 ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == len(__lowerCamelCase ): print(__lowerCamelCase ) return create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _snake_case : list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
81
0
import argparse import json import math import os import time import traceback import zipfile from collections import Counter import requests def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Optional[Any]=None ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() SCREAMING_SNAKE_CASE__ = {} try: job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) SCREAMING_SNAKE_CASE__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = requests.get(url + f'''&page={i + 2}''' , headers=UpperCamelCase__ ).json() job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} ) return job_links except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: str=None ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100''' SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ ).json() SCREAMING_SNAKE_CASE__ = {} try: artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) SCREAMING_SNAKE_CASE__ = math.ceil((result["""total_count"""] - 100) / 100 ) for i in range(UpperCamelCase__ ): SCREAMING_SNAKE_CASE__ = requests.get(url + f'''&page={i + 2}''' , headers=UpperCamelCase__ ).json() artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} ) return artifacts except Exception: print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[Any] , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[Any] ): SCREAMING_SNAKE_CASE__ = None if token is not None: SCREAMING_SNAKE_CASE__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''} SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , headers=UpperCamelCase__ , allow_redirects=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = result.headers["""Location"""] SCREAMING_SNAKE_CASE__ = requests.get(UpperCamelCase__ , allow_redirects=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = os.path.join(UpperCamelCase__ , f'''{artifact_name}.zip''' ) with open(UpperCamelCase__ , """wb""" ) as fp: fp.write(response.content ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = None with zipfile.ZipFile(UpperCamelCase__ ) as z: for filename in z.namelist(): if not os.path.isdir(UpperCamelCase__ ): # read the file if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: with z.open(UpperCamelCase__ ) as f: for line in f: SCREAMING_SNAKE_CASE__ = line.decode("""UTF-8""" ).strip() if filename == "failures_line.txt": try: # `error_line` is the place where `error` occurs SCREAMING_SNAKE_CASE__ = line[: line.index(""": """ )] SCREAMING_SNAKE_CASE__ = line[line.index(""": """ ) + len(""": """ ) :] errors.append([error_line, error] ) except Exception: # skip un-related lines pass elif filename == "summary_short.txt" and line.startswith("""FAILED """ ): # `test` is the test method that failed SCREAMING_SNAKE_CASE__ = line[len("""FAILED """ ) :] failed_tests.append(UpperCamelCase__ ) elif filename == "job_name.txt": SCREAMING_SNAKE_CASE__ = line if len(UpperCamelCase__ ) != len(UpperCamelCase__ ): raise ValueError( f'''`errors` and `failed_tests` should have the same number of elements. Got {len(UpperCamelCase__ )} for `errors` ''' f'''and {len(UpperCamelCase__ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some''' """ problem.""" ) SCREAMING_SNAKE_CASE__ = None if job_name and job_links: SCREAMING_SNAKE_CASE__ = job_links.get(UpperCamelCase__ , UpperCamelCase__ ) # A list with elements of the form (line of error, error, failed test) SCREAMING_SNAKE_CASE__ = [x + [y] + [job_link] for x, y in zip(UpperCamelCase__ , UpperCamelCase__ )] return result def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [os.path.join(UpperCamelCase__ , UpperCamelCase__ ) for p in os.listdir(UpperCamelCase__ ) if p.endswith(""".zip""" )] for p in paths: errors.extend(get_errors_from_single_artifact(UpperCamelCase__ , job_links=UpperCamelCase__ ) ) return errors def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: int , UpperCamelCase__: str=None ): SCREAMING_SNAKE_CASE__ = Counter() counter.update([x[1] for x in logs] ) SCREAMING_SNAKE_CASE__ = counter.most_common() SCREAMING_SNAKE_CASE__ = {} for error, count in counts: if error_filter is None or error not in error_filter: SCREAMING_SNAKE_CASE__ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]} SCREAMING_SNAKE_CASE__ = dict(sorted(r.items() , key=lambda UpperCamelCase__ : item[1]["count"] , reverse=UpperCamelCase__ ) ) return r def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = test.split("""::""" )[0] if test.startswith("""tests/models/""" ): SCREAMING_SNAKE_CASE__ = test.split("""/""" )[2] else: SCREAMING_SNAKE_CASE__ = None return test def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple , UpperCamelCase__: Any=None ): SCREAMING_SNAKE_CASE__ = [(x[0], x[1], get_model(x[2] )) for x in logs] SCREAMING_SNAKE_CASE__ = [x for x in logs if x[2] is not None] SCREAMING_SNAKE_CASE__ = {x[2] for x in logs} SCREAMING_SNAKE_CASE__ = {} for test in tests: SCREAMING_SNAKE_CASE__ = Counter() # count by errors in `test` counter.update([x[1] for x in logs if x[2] == test] ) SCREAMING_SNAKE_CASE__ = counter.most_common() SCREAMING_SNAKE_CASE__ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} SCREAMING_SNAKE_CASE__ = sum(error_counts.values() ) if n_errors > 0: SCREAMING_SNAKE_CASE__ = {"""count""": n_errors, """errors""": error_counts} SCREAMING_SNAKE_CASE__ = dict(sorted(r.items() , key=lambda UpperCamelCase__ : item[1]["count"] , reverse=UpperCamelCase__ ) ) return r def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = """| no. | error | status |""" SCREAMING_SNAKE_CASE__ = """|-:|:-|:-|""" SCREAMING_SNAKE_CASE__ = [header, sep] for error in reduced_by_error: SCREAMING_SNAKE_CASE__ = reduced_by_error[error]["""count"""] SCREAMING_SNAKE_CASE__ = f'''| {count} | {error[:100]} | |''' lines.append(UpperCamelCase__ ) return "\n".join(UpperCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Tuple ): SCREAMING_SNAKE_CASE__ = """| model | no. of errors | major error | count |""" SCREAMING_SNAKE_CASE__ = """|-:|-:|-:|-:|""" SCREAMING_SNAKE_CASE__ = [header, sep] for model in reduced_by_model: SCREAMING_SNAKE_CASE__ = reduced_by_model[model]["""count"""] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = list(reduced_by_model[model]["""errors"""].items() )[0] SCREAMING_SNAKE_CASE__ = f'''| {model} | {count} | {error[:60]} | {_count} |''' lines.append(UpperCamelCase__ ) return "\n".join(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') parser.add_argument( '--output_dir', type=str, required=True, help='Where to store the downloaded artifacts and other result files.', ) parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.') _lowerCamelCase = parser.parse_args() os.makedirs(args.output_dir, exist_ok=True) _lowerCamelCase = get_job_links(args.workflow_run_id, token=args.token) _lowerCamelCase = {} # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. if _job_links: for k, v in _job_links.items(): # This is how GitHub actions combine job names. if " / " in k: _lowerCamelCase = k.find(' / ') _lowerCamelCase = k[index + len(' / ') :] _lowerCamelCase = v with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp: json.dump(job_links, fp, ensure_ascii=False, indent=4) _lowerCamelCase = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) for idx, (name, url) in enumerate(artifacts.items()): download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) _lowerCamelCase = get_all_errors(args.output_dir, job_links=job_links) # `e[1]` is the error _lowerCamelCase = Counter() counter.update([e[1] for e in errors]) # print the top 30 most common test errors _lowerCamelCase = counter.most_common(30) for item in most_common: print(item) with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp: json.dump(errors, fp, ensure_ascii=False, indent=4) _lowerCamelCase = reduce_by_error(errors) _lowerCamelCase = reduce_by_model(errors) _lowerCamelCase = make_github_table(reduced_by_error) _lowerCamelCase = make_github_table_per_model(reduced_by_model) with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa) with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp: fp.write(sa)
6
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
0
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _snake_case ( _snake_case : Optional[int] , _snake_case : Optional[Any]=10 ) -> Optional[int]: '''simple docstring''' _A = [] for _ in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _snake_case ( _snake_case : Optional[Any] , _snake_case : Union[str, Any]=10 ) -> List[str]: '''simple docstring''' _A = [] for step in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _A = os.path.join(_snake_case , 'schedule.bin' ) torch.save(scheduler.state_dict() , _snake_case ) _A = torch.load(_snake_case ) scheduler.load_state_dict(_snake_case ) return lrs @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : List[Any] , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Tuple ): self.assertEqual(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) ) for a, b in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertAlmostEqual(_UpperCAmelCase , _UpperCAmelCase , delta=_UpperCAmelCase ) def lowerCAmelCase_ ( self : Any ): _A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_UpperCAmelCase ) _A = torch.tensor([0.4, 0.2, -0.5] ) _A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(100 ): _A = criterion(_UpperCAmelCase , _UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCAmelCase_ ( self : int ): _A = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_UpperCAmelCase ) _A = torch.tensor([0.4, 0.2, -0.5] ) _A = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _A = Adafactor( params=[w] , lr=1E-2 , eps=(1E-3_0, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_UpperCAmelCase , weight_decay=0.0 , relative_step=_UpperCAmelCase , scale_parameter=_UpperCAmelCase , warmup_init=_UpperCAmelCase , ) for _ in range(1_000 ): _A = criterion(_UpperCAmelCase , _UpperCAmelCase ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class lowercase_ ( unittest.TestCase ): '''simple docstring''' UpperCAmelCase : List[str] = nn.Linear(50 , 50 ) if is_torch_available() else None UpperCAmelCase : Tuple = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None UpperCAmelCase : Dict = 10 def lowerCAmelCase_ ( self : Any , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : List[Any] , _UpperCAmelCase : List[Any]=None ): self.assertEqual(len(_UpperCAmelCase ) , len(_UpperCAmelCase ) ) for a, b in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertAlmostEqual(_UpperCAmelCase , _UpperCAmelCase , delta=_UpperCAmelCase , msg=_UpperCAmelCase ) def lowerCAmelCase_ ( self : List[Any] ): _A = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _A = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _A , _A = data _A = scheduler_func(self.optimizer , **_UpperCAmelCase ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _A = unwrap_schedule(_UpperCAmelCase , self.num_steps ) self.assertListAlmostEqual( _UpperCAmelCase , _UpperCAmelCase , tol=1E-2 , msg=F'''failed for {scheduler_func} in normal scheduler''' , ) _A = scheduler_func(self.optimizer , **_UpperCAmelCase ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_UpperCAmelCase ) # wrap to test picklability of the schedule _A = unwrap_and_save_reload_schedule(_UpperCAmelCase , self.num_steps ) self.assertListEqual(_UpperCAmelCase , _UpperCAmelCase , msg=F'''failed for {scheduler_func} in save and reload''' ) class lowercase_ : '''simple docstring''' def __init__( self : Union[str, Any] , _UpperCAmelCase : Optional[int] ): _A = fn def __call__( self : Tuple , *_UpperCAmelCase : List[str] , **_UpperCAmelCase : List[str] ): return self.fn(*_UpperCAmelCase , **_UpperCAmelCase ) @classmethod def lowerCAmelCase_ ( self : Union[str, Any] , _UpperCAmelCase : Any ): _A = list(map(self , scheduler.lr_lambdas ) )
7
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 a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).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() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).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() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = 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 __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = 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": __snake_case : Union[str, Any] = 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": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
0
'''simple docstring''' def _lowerCAmelCase ( __snake_case : int , __snake_case : int ) -> int: while b: __A ,__A : str = b, a % b return a def _lowerCAmelCase ( __snake_case : int , __snake_case : int ) -> int: return a if b == 0 else euclidean_gcd_recursive(__snake_case , a % b ) def _lowerCAmelCase ( ) -> Any: print(f'euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}' ) print(f'euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}' ) print(f'euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}' ) print(f'euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}' ) print(f'euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}' ) print(f'euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}' ) print(f'euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}' ) print(f'euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}' ) print(f'euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}' ) print(f'euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}' ) if __name__ == "__main__": main()
8
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _snake_case : Optional[int] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[Any] , *lowerCamelCase : Any , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
0
from math import factorial, radians def A ( __UpperCamelCase , __UpperCamelCase = 18 , __UpperCamelCase = 10 ) -> float: A__ = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians A__ = radians(__UpperCamelCase ) A__ = angle_in_radians A__ = 3 A__ = -1 for _ in range(__UpperCamelCase ): result += (b * (angle_in_radians**a)) / factorial(__UpperCamelCase ) A__ = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(__UpperCamelCase , __UpperCamelCase ) if __name__ == "__main__": __import__('''doctest''').testmod()
9
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Any = SamImageProcessor() __snake_case : Optional[int] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Optional[int] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : int ) -> List[Any]: __snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[Any] ) -> Dict: __snake_case : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : List[str] ) -> Tuple: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Optional[int] = self.prepare_image_inputs() __snake_case : List[str] = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : Dict = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Tuple = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[str] = [torch.ones((1, 3, 5, 5) )] __snake_case : Tuple = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : int = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , torch.tensor(lowerCamelCase ) , torch.tensor(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : List[str] = [np.ones((1, 3, 5, 5) )] __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : str = [[1, 0], [0, 1]] with self.assertRaises(lowerCamelCase ): __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) @require_vision @require_tf class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : int = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : str , **lowerCamelCase : Any ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : Dict = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : int ) -> List[str]: __snake_case : List[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: __snake_case : str = self.get_image_processor() __snake_case : Union[str, Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : int = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : List[str] = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def __snake_case ( self : Any ) -> Optional[int]: __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Union[str, Any] = [tf.ones((1, 3, 5, 5) )] __snake_case : List[Any] = [[1764, 2646]] __snake_case : Dict = [[683, 1024]] __snake_case : List[str] = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , tf.convert_to_tensor(lowerCamelCase ) , tf.convert_to_tensor(lowerCamelCase ) , return_tensors="tf" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : Union[str, Any] = [np.ones((1, 3, 5, 5) )] __snake_case : List[str] = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Tuple = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __snake_case : Dict = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[str] , **lowerCamelCase : Any ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : str = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __snake_case : Dict = [tf.convert_to_tensor(lowerCamelCase )] __snake_case : List[Any] = [torch.tensor(lowerCamelCase )] __snake_case : Optional[Any] = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : Union[str, Any] = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) __snake_case : Dict = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : Any = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : Any = image_processor(lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Optional[Any] = processor(images=lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Tuple = image_processor(lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() __snake_case : List[Any] = processor(images=lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) )
81
0
import tempfile import torch from diffusers import PNDMScheduler from .test_schedulers import SchedulerCommonTest class lowerCAmelCase_ ( __lowercase ): UpperCAmelCase = (PNDMScheduler,) UpperCAmelCase = (("num_inference_steps", 50),) def UpperCamelCase_ ( self : str , **_A : Dict ): _UpperCamelCase = { '''num_train_timesteps''': 1000, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**_A ) return config def UpperCamelCase_ ( self : int , _A : Tuple=0 , **_A : Optional[int] ): _UpperCamelCase = dict(self.forward_default_kwargs ) _UpperCamelCase = kwargs.pop('''num_inference_steps''' , _A ) _UpperCamelCase = self.dummy_sample _UpperCamelCase = 0.1 * sample _UpperCamelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _UpperCamelCase = self.get_scheduler_config(**_A ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(_A ) # copy over dummy past residuals _UpperCamelCase = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_A ) _UpperCamelCase = scheduler_class.from_pretrained(_A ) new_scheduler.set_timesteps(_A ) # copy over dummy past residuals _UpperCamelCase = dummy_past_residuals[:] _UpperCamelCase = scheduler.step_prk(_A , _A , _A , **_A ).prev_sample _UpperCamelCase = new_scheduler.step_prk(_A , _A , _A , **_A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" _UpperCamelCase = scheduler.step_plms(_A , _A , _A , **_A ).prev_sample _UpperCamelCase = new_scheduler.step_plms(_A , _A , _A , **_A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : Optional[Any] ): pass def UpperCamelCase_ ( self : List[str] , _A : str=0 , **_A : str ): _UpperCamelCase = dict(self.forward_default_kwargs ) _UpperCamelCase = kwargs.pop('''num_inference_steps''' , _A ) _UpperCamelCase = self.dummy_sample _UpperCamelCase = 0.1 * sample _UpperCamelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(_A ) # copy over dummy past residuals (must be after setting timesteps) _UpperCamelCase = dummy_past_residuals[:] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_A ) _UpperCamelCase = scheduler_class.from_pretrained(_A ) # copy over dummy past residuals new_scheduler.set_timesteps(_A ) # copy over dummy past residual (must be after setting timesteps) _UpperCamelCase = dummy_past_residuals[:] _UpperCamelCase = scheduler.step_prk(_A , _A , _A , **_A ).prev_sample _UpperCamelCase = new_scheduler.step_prk(_A , _A , _A , **_A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" _UpperCamelCase = scheduler.step_plms(_A , _A , _A , **_A ).prev_sample _UpperCamelCase = new_scheduler.step_plms(_A , _A , _A , **_A ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def UpperCamelCase_ ( self : str , **_A : Any ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(**_A ) _UpperCamelCase = scheduler_class(**_A ) _UpperCamelCase = 10 _UpperCamelCase = self.dummy_model() _UpperCamelCase = self.dummy_sample_deter scheduler.set_timesteps(_A ) for i, t in enumerate(scheduler.prk_timesteps ): _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step_prk(_A , _A , _A ).prev_sample for i, t in enumerate(scheduler.plms_timesteps ): _UpperCamelCase = model(_A , _A ) _UpperCamelCase = scheduler.step_plms(_A , _A , _A ).prev_sample return sample def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = dict(self.forward_default_kwargs ) _UpperCamelCase = kwargs.pop('''num_inference_steps''' , _A ) for scheduler_class in self.scheduler_classes: _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) _UpperCamelCase = self.dummy_sample _UpperCamelCase = 0.1 * sample if num_inference_steps is not None and hasattr(_A , '''set_timesteps''' ): scheduler.set_timesteps(_A ) elif num_inference_steps is not None and not hasattr(_A , '''set_timesteps''' ): _UpperCamelCase = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) _UpperCamelCase = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] _UpperCamelCase = dummy_past_residuals[:] _UpperCamelCase = scheduler.step_prk(_A , 0 , _A , **_A ).prev_sample _UpperCamelCase = scheduler.step_prk(_A , 1 , _A , **_A ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) _UpperCamelCase = scheduler.step_plms(_A , 0 , _A , **_A ).prev_sample _UpperCamelCase = scheduler.step_plms(_A , 1 , _A , **_A ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def UpperCamelCase_ ( self : Any ): for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=_A ) def UpperCamelCase_ ( self : Tuple ): for steps_offset in [0, 1]: self.check_over_configs(steps_offset=_A ) _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config(steps_offset=1 ) _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(10 ) assert torch.equal( scheduler.timesteps , torch.LongTensor( [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1] ) , ) def UpperCamelCase_ ( self : List[str] ): for beta_start, beta_end in zip([0.0001, 0.001] , [0.002, 0.02] ): self.check_over_configs(beta_start=_A , beta_end=_A ) def UpperCamelCase_ ( self : str ): for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_A ) def UpperCamelCase_ ( self : Dict ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_A ) def UpperCamelCase_ ( self : Union[str, Any] ): for t in [1, 5, 10]: self.check_over_forward(time_step=_A ) def UpperCamelCase_ ( self : Tuple ): for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=_A ) def UpperCamelCase_ ( self : Dict ): # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3 _UpperCamelCase = 27 for scheduler_class in self.scheduler_classes: _UpperCamelCase = self.dummy_sample _UpperCamelCase = 0.1 * sample _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.set_timesteps(_A ) # before power of 3 fix, would error on first step, so we only need to do two for i, t in enumerate(scheduler.prk_timesteps[:2] ): _UpperCamelCase = scheduler.step_prk(_A , _A , _A ).prev_sample def UpperCamelCase_ ( self : Union[str, Any] ): with self.assertRaises(_A ): _UpperCamelCase = self.scheduler_classes[0] _UpperCamelCase = self.get_scheduler_config() _UpperCamelCase = scheduler_class(**_A ) scheduler.step_plms(self.dummy_sample , 1 , self.dummy_sample ).prev_sample def UpperCamelCase_ ( self : Any ): _UpperCamelCase = self.full_loop() _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 198.1318 ) < 1e-2 assert abs(result_mean.item() - 0.2580 ) < 1e-3 def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = self.full_loop(prediction_type='''v_prediction''' ) _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 67.3986 ) < 1e-2 assert abs(result_mean.item() - 0.0878 ) < 1e-3 def UpperCamelCase_ ( self : str ): # We specify different beta, so that the first alpha is 0.99 _UpperCamelCase = self.full_loop(set_alpha_to_one=_A , beta_start=0.01 ) _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 230.0399 ) < 1e-2 assert abs(result_mean.item() - 0.2995 ) < 1e-3 def UpperCamelCase_ ( self : Any ): # We specify different beta, so that the first alpha is 0.99 _UpperCamelCase = self.full_loop(set_alpha_to_one=_A , beta_start=0.01 ) _UpperCamelCase = torch.sum(torch.abs(_A ) ) _UpperCamelCase = torch.mean(torch.abs(_A ) ) assert abs(result_sum.item() - 186.9482 ) < 1e-2 assert abs(result_mean.item() - 0.2434 ) < 1e-3
10
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowerCamelCase : str , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
0
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { "facebook/wav2vec2-base-960h": "https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json", # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class __A ( A ): '''simple docstring''' __lowerCamelCase : str = 'wav2vec2' def __init__(self , A=32 , A=768 , A=12 , A=12 , A=3_072 , A="gelu" , A=0.1 , A=0.1 , A=0.1 , A=0.0 , A=0.0 , A=0.1 , A=0.1 , A=0.02 , A=1E-5 , A="group" , A="gelu" , A=(512, 512, 512, 512, 512, 512, 512) , A=(5, 2, 2, 2, 2, 2, 2) , A=(10, 3, 3, 3, 3, 2, 2) , A=False , A=128 , A=16 , A=False , A=True , A=0.05 , A=10 , A=2 , A=0.0 , A=10 , A=0 , A=320 , A=2 , A=0.1 , A=100 , A=256 , A=256 , A=0.1 , A="sum" , A=False , A=False , A=256 , A=(512, 512, 512, 512, 1_500) , A=(5, 3, 3, 1, 1) , A=(1, 2, 3, 1, 1) , A=512 , A=0 , A=1 , A=2 , A=False , A=3 , A=2 , A=3 , A=None , A=None , **A , ) -> int: """simple docstring""" super().__init__(**A , pad_token_id=A , bos_token_id=A , eos_token_id=A ) _a = hidden_size _a = feat_extract_norm _a = feat_extract_activation _a = list(A ) _a = list(A ) _a = list(A ) _a = conv_bias _a = num_conv_pos_embeddings _a = num_conv_pos_embedding_groups _a = len(self.conv_dim ) _a = num_hidden_layers _a = intermediate_size _a = hidden_act _a = num_attention_heads _a = hidden_dropout _a = attention_dropout _a = activation_dropout _a = feat_proj_dropout _a = final_dropout _a = layerdrop _a = layer_norm_eps _a = initializer_range _a = vocab_size _a = do_stable_layer_norm _a = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _a = apply_spec_augment _a = mask_time_prob _a = mask_time_length _a = mask_time_min_masks _a = mask_feature_prob _a = mask_feature_length _a = mask_feature_min_masks # parameters for pretraining with codevector quantized representations _a = num_codevectors_per_group _a = num_codevector_groups _a = contrastive_logits_temperature _a = feat_quantizer_dropout _a = num_negatives _a = codevector_dim _a = proj_codevector_dim _a = diversity_loss_weight # ctc loss _a = ctc_loss_reduction _a = ctc_zero_infinity # adapter _a = add_adapter _a = adapter_kernel_size _a = adapter_stride _a = num_adapter_layers _a = output_hidden_size or hidden_size _a = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. _a = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _a = list(A ) _a = list(A ) _a = list(A ) _a = xvector_output_dim @property def a__ (self ) -> Optional[Any]: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
11
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case : Union[str, Any] = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["OwlViTFeatureExtractor"] _snake_case : Optional[int] = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _snake_case : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType lowerCamelCase__ : int = logging.get_logger(__name__) lowerCamelCase__ : int = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off lowerCamelCase__ : Dict = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_7, 3_6_6, 4_3_8, 5_3_2, 6_8_5, 7_0_5, 7_9_6, 9_3_0, 1_0_5_8, 1_2_2_0, 1_2_6_7, 1_2_7_9, 1_3_0_3, 1_3_4_3, 1_3_7_7, 1_3_9_1, 1_6_3_5, 1_7_8_2, 1_8_7_5, 2_1_6_2, 2_3_6_1, 2_4_8_8, 3_4_6_7, 4_0_0_8, 4_2_1_1, 4_6_0_0, 4_8_0_8, 5_2_9_9, 5_8_5_5, 6_3_2_9, 7_2_0_3, 9_6_0_9, 9_9_5_9, 1_0_5_6_3, 1_0_7_8_6, 1_1_4_2_0, 1_1_7_0_9, 1_1_9_0_7, 1_3_1_6_3, 1_3_6_9_7, 1_3_7_0_0, 1_4_8_0_8, 1_5_3_0_6, 1_6_4_1_0, 1_6_7_9_1, 1_7_9_9_2, 1_9_2_0_3, 1_9_5_1_0, 2_0_7_2_4, 2_2_3_0_5, 2_2_9_3_5, 2_7_0_0_7, 3_0_1_0_9, 3_0_4_2_0, 3_3_4_0_9, 3_4_9_4_9, 4_0_2_8_3, 4_0_4_9_3, 4_0_5_4_9, 4_7_2_8_2, 4_9_1_4_6, 5_0_2_5_7, 5_0_3_5_9, 5_0_3_6_0, 5_0_3_6_1 ] lowerCamelCase__ : str = [ 1, 2, 7, 8, 9, 1_0, 1_4, 2_5, 2_6, 2_7, 2_8, 2_9, 3_1, 5_8, 5_9, 6_0, 6_1, 6_2, 6_3, 9_0, 9_1, 9_2, 9_3, 3_5_9, 5_0_3, 5_2_2, 5_4_2, 8_7_3, 8_9_3, 9_0_2, 9_1_8, 9_2_2, 9_3_1, 1_3_5_0, 1_8_5_3, 1_9_8_2, 2_4_6_0, 2_6_2_7, 3_2_4_6, 3_2_5_3, 3_2_6_8, 3_5_3_6, 3_8_4_6, 3_9_6_1, 4_1_8_3, 4_6_6_7, 6_5_8_5, 6_6_4_7, 7_2_7_3, 9_0_6_1, 9_3_8_3, 1_0_4_2_8, 1_0_9_2_9, 1_1_9_3_8, 1_2_0_3_3, 1_2_3_3_1, 1_2_5_6_2, 1_3_7_9_3, 1_4_1_5_7, 1_4_6_3_5, 1_5_2_6_5, 1_5_6_1_8, 1_6_5_5_3, 1_6_6_0_4, 1_8_3_6_2, 1_8_9_5_6, 2_0_0_7_5, 2_1_6_7_5, 2_2_5_2_0, 2_6_1_3_0, 2_6_1_6_1, 2_6_4_3_5, 2_8_2_7_9, 2_9_4_6_4, 3_1_6_5_0, 3_2_3_0_2, 3_2_4_7_0, 3_6_8_6_5, 4_2_8_6_3, 4_7_4_2_5, 4_9_8_7_0, 5_0_2_5_4, 5_0_2_5_8, 5_0_3_6_0, 5_0_3_6_1, 5_0_3_6_2 ] class _snake_case ( UpperCAmelCase_ ): __lowerCAmelCase : List[str] = 'whisper' __lowerCAmelCase : str = ['past_key_values'] __lowerCAmelCase : Optional[int] = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , SCREAMING_SNAKE_CASE_=5_18_65 , SCREAMING_SNAKE_CASE_=80 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=15_36 , SCREAMING_SNAKE_CASE_=15_36 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=5_02_57 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0_2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=15_00 , SCREAMING_SNAKE_CASE_=4_48 , SCREAMING_SNAKE_CASE_=5_02_56 , SCREAMING_SNAKE_CASE_=5_02_56 , SCREAMING_SNAKE_CASE_=5_02_56 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=[2_20, 5_02_56] , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=2_56 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=0.0_5 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=7 , **SCREAMING_SNAKE_CASE_ , ): '''simple docstring''' lowercase__ : str = vocab_size lowercase__ : Tuple = num_mel_bins lowercase__ : int = d_model lowercase__ : str = encoder_layers lowercase__ : str = encoder_attention_heads lowercase__ : Any = decoder_layers lowercase__ : Optional[int] = decoder_attention_heads lowercase__ : List[str] = decoder_ffn_dim lowercase__ : Dict = encoder_ffn_dim lowercase__ : Dict = dropout lowercase__ : Dict = attention_dropout lowercase__ : List[str] = activation_dropout lowercase__ : List[str] = activation_function lowercase__ : Dict = init_std lowercase__ : int = encoder_layerdrop lowercase__ : List[str] = decoder_layerdrop lowercase__ : List[str] = use_cache lowercase__ : Tuple = encoder_layers lowercase__ : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True lowercase__ : int = max_source_positions lowercase__ : Tuple = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. lowercase__ : Tuple = classifier_proj_size lowercase__ : Optional[int] = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase__ : Optional[int] = apply_spec_augment lowercase__ : Any = mask_time_prob lowercase__ : str = mask_time_length lowercase__ : int = mask_time_min_masks lowercase__ : List[Any] = mask_feature_prob lowercase__ : List[Any] = mask_feature_length lowercase__ : Optional[int] = mask_feature_min_masks lowercase__ : Dict = median_filter_width super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , is_encoder_decoder=SCREAMING_SNAKE_CASE_ , decoder_start_token_id=SCREAMING_SNAKE_CASE_ , suppress_tokens=SCREAMING_SNAKE_CASE_ , begin_suppress_tokens=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) class _snake_case ( UpperCAmelCase_ ): @property def lowercase__ ( self): '''simple docstring''' lowercase__ : int = OrderedDict( [ ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}), ]) if self.use_past: lowercase__ : List[str] = {0: """batch"""} else: lowercase__ : int = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_ , direction="""inputs""") return common_inputs def lowercase__ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = -1 , SCREAMING_SNAKE_CASE_ = False , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = 2_20_50 , SCREAMING_SNAKE_CASE_ = 5.0 , SCREAMING_SNAKE_CASE_ = 2_20 , ): '''simple docstring''' lowercase__ : str = OrderedDict() lowercase__ : List[Any] = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=SCREAMING_SNAKE_CASE_ , framework=SCREAMING_SNAKE_CASE_ , sampling_rate=SCREAMING_SNAKE_CASE_ , time_duration=SCREAMING_SNAKE_CASE_ , frequency=SCREAMING_SNAKE_CASE_ , ) lowercase__ : Dict = encoder_inputs["""input_features"""].shape[2] lowercase__ : List[Any] = encoder_sequence_length // 2 if self.use_past else seq_length lowercase__ : Optional[Any] = super().generate_dummy_inputs( preprocessor.tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_) lowercase__ : List[str] = encoder_inputs.pop("""input_features""") lowercase__ : Optional[Any] = decoder_inputs.pop("""decoder_input_ids""") if "past_key_values" in decoder_inputs: lowercase__ : Dict = decoder_inputs.pop("""past_key_values""") return dummy_inputs @property def lowercase__ ( self): '''simple docstring''' return 1E-3
12
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : str = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "van" def __init__( self : Optional[int] , lowerCamelCase : Any=224 , lowerCamelCase : str=3 , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : Dict=[4, 2, 2, 2] , lowerCamelCase : List[Any]=[64, 128, 320, 512] , lowerCamelCase : str=[3, 3, 12, 3] , lowerCamelCase : Dict=[8, 8, 4, 4] , lowerCamelCase : Any="gelu" , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Tuple=1E-6 , lowerCamelCase : Optional[int]=1E-2 , lowerCamelCase : int=0.0 , lowerCamelCase : Optional[Any]=0.0 , **lowerCamelCase : Optional[int] , ) -> int: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = image_size __snake_case : Any = num_channels __snake_case : Any = patch_sizes __snake_case : List[Any] = strides __snake_case : str = hidden_sizes __snake_case : Dict = depths __snake_case : Optional[int] = mlp_ratios __snake_case : Dict = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : Optional[int] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : int = dropout_rate
81
0
'''simple docstring''' import os import string import sys A__ : Tuple = 1 << 8 A__ : Dict = { """tab""": ord("""\t"""), """newline""": ord("""\r"""), """esc""": 27, """up""": 65 + ARROW_KEY_FLAG, """down""": 66 + ARROW_KEY_FLAG, """right""": 67 + ARROW_KEY_FLAG, """left""": 68 + ARROW_KEY_FLAG, """mod_int""": 91, """undefined""": sys.maxsize, """interrupt""": 3, """insert""": 50, """delete""": 51, """pg_up""": 53, """pg_down""": 54, } A__ : Optional[int] = KEYMAP["""up"""] A__ : Optional[int] = KEYMAP["""left"""] if sys.platform == "win32": A__ : str = [] A__ : str = { B"""\xe0H""": KEYMAP["""up"""] - ARROW_KEY_FLAG, B"""\x00H""": KEYMAP["""up"""] - ARROW_KEY_FLAG, B"""\xe0P""": KEYMAP["""down"""] - ARROW_KEY_FLAG, B"""\x00P""": KEYMAP["""down"""] - ARROW_KEY_FLAG, B"""\xe0M""": KEYMAP["""right"""] - ARROW_KEY_FLAG, B"""\x00M""": KEYMAP["""right"""] - ARROW_KEY_FLAG, B"""\xe0K""": KEYMAP["""left"""] - ARROW_KEY_FLAG, B"""\x00K""": KEYMAP["""left"""] - ARROW_KEY_FLAG, } for i in range(10): A__ : Optional[Any] = ord(str(i)) def UpperCAmelCase__ ( ) -> int: if os.name == "nt": import msvcrt __lowerCamelCase : Any = 'mbcs' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(UpperCAmelCase_ ) == 0: # Read the keystroke __lowerCamelCase : List[Any] = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): __lowerCamelCase : List[Any] = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: __lowerCamelCase : str = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['mod_int'] ) ) WIN_CH_BUFFER.append(UpperCAmelCase_ ) if ord(UpperCAmelCase_ ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) __lowerCamelCase : List[Any] = chr(KEYMAP['esc'] ) except KeyError: __lowerCamelCase : Optional[int] = cha[1] else: __lowerCamelCase : List[str] = ch.decode(UpperCAmelCase_ ) else: __lowerCamelCase : Dict = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty __lowerCamelCase : str = sys.stdin.fileno() __lowerCamelCase : Union[str, Any] = termios.tcgetattr(UpperCAmelCase_ ) try: tty.setraw(UpperCAmelCase_ ) __lowerCamelCase : Union[str, Any] = sys.stdin.read(1 ) finally: termios.tcsetattr(UpperCAmelCase_ , termios.TCSADRAIN , UpperCAmelCase_ ) return ch def UpperCAmelCase__ ( ) -> List[str]: __lowerCamelCase : Tuple = get_raw_chars() if ord(UpperCAmelCase_ ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(UpperCAmelCase_ ) == KEYMAP["esc"]: __lowerCamelCase : List[str] = get_raw_chars() if ord(UpperCAmelCase_ ) == KEYMAP["mod_int"]: __lowerCamelCase : Optional[Any] = get_raw_chars() if ord(UpperCAmelCase_ ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(UpperCAmelCase_ ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(UpperCAmelCase_ ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
13
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case : Union[str, Any] = logging.getLogger(__name__) def lowerCAmelCase_ ( ): __snake_case : int = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __snake_case : List[str] = parser.parse_args() return args def lowerCAmelCase_ ( __lowerCamelCase ): def fn(__lowerCamelCase ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = [] for i in range(len(tokenized_data["input_ids"] ) ): __snake_case : Tuple = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase ) __snake_case : str = tf.train.Example(features=__lowerCamelCase ) __snake_case : List[str] = example.SerializeToString() records.append(__lowerCamelCase ) return records def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) __snake_case : Dict = dataset.select(range(__lowerCamelCase ) ) print(F'Limiting the dataset to {args.limit} entries.' ) __snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __snake_case : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: __snake_case : str = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __snake_case : Any = tokenize_function(__lowerCamelCase ) __snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__lowerCamelCase ): # Concatenate all texts. __snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()} __snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __snake_case : int = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result __snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 ) __snake_case : Optional[Any] = 0 __snake_case : Optional[Any] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): __snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size] __snake_case : Any = len(dataset_snapshot["input_ids"] ) __snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' ) __snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): __snake_case : Union[str, Any] = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase ) if __name__ == "__main__": _snake_case : List[Any] = parse_args() main(args)
81
0
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __UpperCAmelCase ( __a : bytes ,__a : int ) -> np.array: """simple docstring""" _a : int = F"""{sampling_rate}""" _a : str = '''1''' _a : Optional[int] = '''f32le''' _a : Optional[Any] = [ '''ffmpeg''', '''-i''', '''pipe:0''', '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] try: with subprocess.Popen(__a ,stdin=subprocess.PIPE ,stdout=subprocess.PIPE ) as ffmpeg_process: _a : Any = ffmpeg_process.communicate(__a ) except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to load audio files from filename''' ) from error _a : Optional[Any] = output_stream[0] _a : Optional[int] = np.frombuffer(__a ,np.floataa ) if audio.shape[0] == 0: raise ValueError('''Malformed soundfile''' ) return audio def __UpperCAmelCase ( __a : int ,__a : float ,__a : str = "f32le" ,) -> str: """simple docstring""" _a : Dict = F"""{sampling_rate}""" _a : Optional[Any] = '''1''' if format_for_conversion == "s16le": _a : Dict = 2 elif format_for_conversion == "f32le": _a : Optional[Any] = 4 else: raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Dict = platform.system() if system == "Linux": _a : Dict = '''alsa''' _a : Union[str, Any] = '''default''' elif system == "Darwin": _a : Union[str, Any] = '''avfoundation''' _a : List[str] = ''':0''' elif system == "Windows": _a : Optional[int] = '''dshow''' _a : str = '''default''' _a : Tuple = [ '''ffmpeg''', '''-f''', format_, '''-i''', input_, '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-fflags''', '''nobuffer''', '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : str = _ffmpeg_stream(__a ,__a ) for item in iterator: yield item def __UpperCAmelCase ( __a : int ,__a : float ,__a : Optional[int] = None ,__a : Optional[Union[Tuple[float, float], float]] = None ,__a : str = "f32le" ,) -> Optional[int]: """simple docstring""" if stream_chunk_s is not None: _a : Tuple = stream_chunk_s else: _a : Tuple = chunk_length_s _a : Tuple = ffmpeg_microphone(__a ,__a ,format_for_conversion=__a ) if format_for_conversion == "s16le": _a : Any = np.intaa _a : Optional[int] = 2 elif format_for_conversion == "f32le": _a : Dict = np.floataa _a : List[Any] = 4 else: raise ValueError(F"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : List[Any] = chunk_length_s / 6 _a : Optional[int] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(__a ,(int, float) ): _a : Optional[Any] = [stride_length_s, stride_length_s] _a : Optional[Any] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : str = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Optional[Any] = datetime.datetime.now() _a : Tuple = datetime.timedelta(seconds=__a ) for item in chunk_bytes_iter(__a ,__a ,stride=(stride_left, stride_right) ,stream=__a ): # Put everything back in numpy scale _a : Dict = np.frombuffer(item['''raw'''] ,dtype=__a ) _a : Dict = ( item['''stride'''][0] // size_of_sample, item['''stride'''][1] // size_of_sample, ) _a : str = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __UpperCAmelCase ( __a : Optional[int] ,__a : int ,__a : Tuple[int, int] ,__a : bool = False ) -> Optional[int]: """simple docstring""" _a : Any = b'''''' _a , _a : List[str] = stride if stride_left + stride_right >= chunk_len: raise ValueError( F"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : List[str] = 0 for raw in iterator: acc += raw if stream and len(__a ) < chunk_len: _a : Dict = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(__a ) >= chunk_len: # We are flushing the accumulator _a : List[str] = (_stride_left, stride_right) _a : List[Any] = {'''raw''': acc[:chunk_len], '''stride''': stride} if stream: _a : List[Any] = False yield item _a : Optional[Any] = stride_left _a : Optional[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(__a ) > stride_left: _a : Optional[Any] = {'''raw''': acc, '''stride''': (_stride_left, 0)} if stream: _a : Dict = False yield item def __UpperCAmelCase ( __a : int ,__a : int ) -> Tuple: """simple docstring""" _a : Dict = 2**24 # 16Mo try: with subprocess.Popen(__a ,stdout=subprocess.PIPE ,bufsize=__a ) as ffmpeg_process: while True: _a : int = ffmpeg_process.stdout.read(__a ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to stream audio files from filename''' ) from error
14
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _snake_case : List[Any] = "\\n Text data.\n Second line of data." _snake_case : Tuple = "file" @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") __snake_case : Optional[Any] = bytes(__lowerCamelCase , "utf-8" ) with zstd.open(__lowerCamelCase , "wb" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture def lowerCAmelCase_ ( __lowerCamelCase ): with open(os.path.join(tmpfs.local_root_dir , __lowerCamelCase ) , "w" ) as f: f.write(__lowerCamelCase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} __snake_case : str = input_paths[compression_format] __snake_case : Optional[Any] = tmp_path / "cache" __snake_case : Optional[int] = DownloadConfig(cache_dir=__lowerCamelCase , extract_compressed_file=__lowerCamelCase ) __snake_case : Union[str, Any] = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) with open(__lowerCamelCase ) as f: __snake_case : Dict = f.read() with open(__lowerCamelCase ) as f: __snake_case : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = "custom_cache" __snake_case : List[str] = "custom_extracted_dir" __snake_case : Any = tmp_path / "custom_extracted_path" if default_extracted: __snake_case : List[Any] = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __lowerCamelCase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__lowerCamelCase ) ) __snake_case : Optional[Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __snake_case : Optional[int] = xz_file __snake_case : Optional[int] = ( DownloadConfig(extract_compressed_file=__lowerCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__lowerCamelCase ) ) __snake_case : str = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) assert Path(__lowerCamelCase ).parent.parts[-2:] == expected def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : Optional[Any] = str(Path(__lowerCamelCase ).resolve() ) assert cached_path(__lowerCamelCase ) == text_file # relative path __snake_case : Any = str(Path(__lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(__lowerCamelCase ) == text_file def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) # relative path __snake_case : Optional[int] = "./__missing_file__.txt" with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : str = get_from_cache(F'tmp://{tmpfs_file}' ) with open(__lowerCamelCase ) as f: __snake_case : Union[str, Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( ): with pytest.raises(__lowerCamelCase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): http_get("https://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[str] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): ftp_get("ftp://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): fsspec_get("s3://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): fsspec_head("s3://huggingface.co" )
81
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin A : Tuple = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class A ( UpperCAmelCase__ , unittest.TestCase ): '''simple docstring''' A__ = GPTSwaTokenizer A__ = False A__ = True A__ = False def lowerCamelCase__ (self : List[Any] ) -> Optional[int]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowercase__ = GPTSwaTokenizer(_UpperCAmelCase , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ (self : Union[str, Any] , _UpperCAmelCase : Any ) -> int: """simple docstring""" lowercase__ = """This is a test""" lowercase__ = """This is a test""" return input_text, output_text def lowerCamelCase__ (self : int ) -> List[Any]: """simple docstring""" lowercase__ = """<s>""" lowercase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) , _UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) , _UpperCAmelCase ) def lowerCamelCase__ (self : Optional[Any] ) -> int: """simple docstring""" lowercase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(_UpperCAmelCase ) , 2000 ) def lowerCamelCase__ (self : Tuple ) -> Dict: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def lowerCamelCase__ (self : Dict ) -> Union[str, Any]: """simple docstring""" lowercase__ = GPTSwaTokenizer(_UpperCAmelCase ) lowercase__ = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_UpperCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , [465, 287, 265, 631, 842] ) lowercase__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) # fmt: off self.assertListEqual( _UpperCAmelCase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , ) # fmt: on lowercase__ = tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) self.assertListEqual( _UpperCAmelCase , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) lowercase__ = tokenizer.convert_ids_to_tokens(_UpperCAmelCase ) # fmt: off self.assertListEqual( _UpperCAmelCase , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ) # fmt: on def lowerCamelCase__ (self : Tuple ) -> List[str]: """simple docstring""" lowercase__ = GPTSwaTokenizer(_UpperCAmelCase ) lowercase__ = ["""This is a test""", """I was born in 92000, and this is falsé."""] lowercase__ = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertListEqual(tokenizer.encode_fast(_UpperCAmelCase ) , _UpperCAmelCase ) # Test that decode_fast returns the input text for text, token_ids in zip(_UpperCAmelCase , _UpperCAmelCase ): self.assertEqual(tokenizer.decode_fast(_UpperCAmelCase ) , _UpperCAmelCase ) @slow def lowerCamelCase__ (self : int ) -> List[Any]: """simple docstring""" lowercase__ = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off lowercase__ = {"""input_ids""": [[6_3423, 5, 6811, 1_4954, 282, 816, 3821, 6_3466, 6_3425, 6_3462, 18, 6_3978, 678, 301, 1320, 6_3423, 6_3455, 6_3458, 18, 6_3982, 4246, 3940, 1901, 4_7789, 5547, 1_8994], [1_9630, 1100, 6_3446, 1342, 633, 544, 4488, 593, 5102, 2416, 6_3495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 5_8593, 2_2413, 9106, 546, 268, 3_3213, 6_3979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5130, 6_3450, 924, 6_3449, 2249, 4062, 1558, 318, 6_3504, 2_1498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 6_3443, 2_6801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=_UpperCAmelCase , )
15
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = start # add current to visited visited.append(__lowerCamelCase ) __snake_case : List[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __snake_case : Tuple = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # if all neighbors visited add current to sort sort.append(__lowerCamelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCamelCase ) != len(__lowerCamelCase ): for vertice in vertices: if vertice not in visited: __snake_case : int = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # return sort return sort if __name__ == "__main__": _snake_case : List[Any] = topological_sort("a", [], []) print(sort)
81
0
import unittest from transformers import AutoTokenizer, FalconConfig, 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 ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class _SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , __lowerCamelCase : List[Any] , __lowerCamelCase : int=3 , __lowerCamelCase : List[str]=7 , __lowerCamelCase : int=True , __lowerCamelCase : Dict=True , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : str=True , __lowerCamelCase : Optional[int]=99 , __lowerCamelCase : Any=32 , __lowerCamelCase : Tuple=5 , __lowerCamelCase : str=4 , __lowerCamelCase : str=37 , __lowerCamelCase : List[Any]="gelu" , __lowerCamelCase : List[Any]=0.1 , __lowerCamelCase : int=0.1 , __lowerCamelCase : Any=512 , __lowerCamelCase : Tuple=16 , __lowerCamelCase : Optional[Any]=2 , __lowerCamelCase : Optional[int]=0.02 , __lowerCamelCase : List[Any]=3 , __lowerCamelCase : Dict=4 , __lowerCamelCase : Optional[Any]=None , ): 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 _snake_case ( self : 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 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 _snake_case ( self : str ): return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=__lowerCamelCase , ) def _snake_case ( self : Union[str, Any] , __lowerCamelCase : List[str] , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] , __lowerCamelCase : Tuple , __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] ): SCREAMING_SNAKE_CASE = FalconModel(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self : Dict , __lowerCamelCase : Dict , __lowerCamelCase : Tuple , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : Optional[int] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : int , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] , ): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = FalconModel(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self : List[str] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[Any] , __lowerCamelCase : Tuple , __lowerCamelCase : Tuple , __lowerCamelCase : int , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , ): SCREAMING_SNAKE_CASE = FalconForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self : str , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : str , __lowerCamelCase : int , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Dict , __lowerCamelCase : List[Any] , ): SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = FalconForCausalLM(config=__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() # first forward pass SCREAMING_SNAKE_CASE = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , use_cache=__lowerCamelCase , ) SCREAMING_SNAKE_CASE = outputs.past_key_values # 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) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["hidden_states"][0] SCREAMING_SNAKE_CASE = model( __lowerCamelCase , attention_mask=__lowerCamelCase , encoder_hidden_states=__lowerCamelCase , encoder_attention_mask=__lowerCamelCase , past_key_values=__lowerCamelCase , output_hidden_states=__lowerCamelCase , )["hidden_states"][0] # select random slice 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(__lowerCamelCase , __lowerCamelCase , atol=1e-3 ) ) def _snake_case ( self : List[Any] ): 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 _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) lowerCamelCase__ = (FalconForCausalLM,) if is_torch_available() else () lowerCamelCase__ = ( { "feature-extraction": FalconModel, "text-classification": FalconForSequenceClassification, "text-generation": FalconForCausalLM, "question-answering": FalconForQuestionAnswering, "token-classification": FalconForTokenClassification, "zero-shot": FalconForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = FalconModelTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self , config_class=__lowerCamelCase , hidden_size=37 ) def _snake_case ( self : int ): self.config_tester.run_common_tests() def _snake_case ( self : List[Any] ): SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCamelCase ) def _snake_case ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: SCREAMING_SNAKE_CASE = alibi self.model_tester.create_and_check_model(__lowerCamelCase , *__lowerCamelCase ) def _snake_case ( self : str ): 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(__lowerCamelCase ) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE = FalconForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = "single_label_classification" SCREAMING_SNAKE_CASE = input_dict["input_ids"] SCREAMING_SNAKE_CASE = input_ids.ne(1 ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE = FalconForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE = input_dict["input_ids"] SCREAMING_SNAKE_CASE = FalconForCausalLM(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , use_cache=__lowerCamelCase ) SCREAMING_SNAKE_CASE = input_ids.shape[0] SCREAMING_SNAKE_CASE = model._convert_to_rw_cache(result.past_key_values ) SCREAMING_SNAKE_CASE = model._convert_cache_to_standard_format(__lowerCamelCase , __lowerCamelCase ) for layer in range(len(__lowerCamelCase ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def _snake_case ( self : List[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(__lowerCamelCase ) 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 = FalconForSequenceClassification(__lowerCamelCase ) model.to(__lowerCamelCase ) model.eval() SCREAMING_SNAKE_CASE = model(__lowerCamelCase , attention_mask=__lowerCamelCase , labels=__lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _snake_case ( self : List[str] ): # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(__lowerCamelCase , "use_cache" ): return SCREAMING_SNAKE_CASE = model_class(__lowerCamelCase ).to(__lowerCamelCase ) if "use_cache" not in inputs: SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = model(**__lowerCamelCase ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return SCREAMING_SNAKE_CASE = ( getattr(__lowerCamelCase , "decoder_layers" , __lowerCamelCase ) or getattr(__lowerCamelCase , "num_decoder_layers" , __lowerCamelCase ) or config.num_hidden_layers ) SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , "num_kv_heads" , config.num_attention_heads ) SCREAMING_SNAKE_CASE = getattr(__lowerCamelCase , "d_model" , config.hidden_size ) SCREAMING_SNAKE_CASE = embed_dim // num_attention_heads SCREAMING_SNAKE_CASE = outputs["past_key_values"] self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = inputs["input_ids"].shape for i in range(__lowerCamelCase ): if config.new_decoder_architecture: SCREAMING_SNAKE_CASE = config.num_attention_heads elif config.multi_query: SCREAMING_SNAKE_CASE = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self : int ): SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained("Rocketknight1/falcon-rw-1b" ) SCREAMING_SNAKE_CASE = FalconForCausalLM.from_pretrained("Rocketknight1/falcon-rw-1b" ) model.eval() model.to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer("My favorite food is" , return_tensors="pt" ).to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = ( "My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday." ) SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase , do_sample=__lowerCamelCase , max_new_tokens=19 ) SCREAMING_SNAKE_CASE = tokenizer.batch_decode(__lowerCamelCase )[0] self.assertEqual(__lowerCamelCase , __lowerCamelCase ) @slow def _snake_case ( self : Union[str, Any] ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = FalconForCausalLM.from_pretrained(__lowerCamelCase ) model.eval() model.to(__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer("My favorite food is" , return_tensors="pt" ).to(__lowerCamelCase ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**__lowerCamelCase , do_sample=__lowerCamelCase , max_new_tokens=4 ) model.generate(**__lowerCamelCase , do_sample=__lowerCamelCase , max_new_tokens=4 ) model.generate(**__lowerCamelCase , num_beams=2 , max_new_tokens=4 ) @slow def _snake_case ( self : int ): # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(__lowerCamelCase ) SCREAMING_SNAKE_CASE = FalconForCausalLM.from_pretrained(__lowerCamelCase ) model.eval() model.to(device=__lowerCamelCase ) SCREAMING_SNAKE_CASE = tokenizer("My favorite food is" , return_tensors="pt" ).to(__lowerCamelCase ) # Test results are the same with and without cache SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase , do_sample=__lowerCamelCase , max_new_tokens=20 , use_cache=__lowerCamelCase ) SCREAMING_SNAKE_CASE = model.generate(**__lowerCamelCase , do_sample=__lowerCamelCase , max_new_tokens=20 , use_cache=__lowerCamelCase ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
16
def lowerCAmelCase_ ( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(__lowerCamelCase , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
81
0
import inspect import unittest import torch import torch.nn as nn from accelerate.hooks import ( AlignDevicesHook, ModelHook, SequentialHook, add_hook_to_module, attach_align_device_hook, remove_hook_from_module, remove_hook_from_submodules, ) from accelerate.test_utils import require_multi_gpu class lowerCamelCase_ ( nn.Module ): def __init__( self : Optional[int] ): super().__init__() __A : Optional[int] = nn.Linear(3 , 4 ) __A : Optional[Any] = nn.BatchNormad(4 ) __A : Optional[int] = nn.Linear(4 , 5 ) def lowerCAmelCase_ ( self : str , __A : Any ): return self.lineara(self.batchnorm(self.lineara(__A ) ) ) class lowerCamelCase_ ( _lowercase ): def lowerCAmelCase_ ( self : Union[str, Any] , __A : int , *__A : List[Any] , **__A : Any ): return (args[0] + 1,) + args[1:], kwargs class lowerCamelCase_ ( _lowercase ): def lowerCAmelCase_ ( self : Optional[int] , __A : List[str] , __A : str ): return output + 1 class lowerCamelCase_ ( unittest.TestCase ): def lowerCAmelCase_ ( self : List[str] ): __A : Union[str, Any] = ModelForTest() __A : Union[str, Any] = ModelHook() add_hook_to_module(__A , __A ) self.assertEqual(test_model._hf_hook , __A ) self.assertTrue(hasattr(__A , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__A ) self.assertFalse(hasattr(__A , """_hf_hook""" ) ) self.assertFalse(hasattr(__A , """_old_forward""" ) ) def lowerCAmelCase_ ( self : Dict ): __A : str = ModelForTest() __A : Tuple = ModelHook() add_hook_to_module(__A , __A ) add_hook_to_module(__A , __A , append=__A ) self.assertEqual(isinstance(test_model._hf_hook , __A ) , __A ) self.assertEqual(len(test_model._hf_hook.hooks ) , 2 ) self.assertTrue(hasattr(__A , """_old_forward""" ) ) # Check adding the hook did not change the name or the signature self.assertEqual(test_model.forward.__name__ , """forward""" ) self.assertListEqual(list(inspect.signature(test_model.forward ).parameters ) , ["""x"""] ) remove_hook_from_module(__A ) self.assertFalse(hasattr(__A , """_hf_hook""" ) ) self.assertFalse(hasattr(__A , """_old_forward""" ) ) def lowerCAmelCase_ ( self : int ): __A : int = ModelForTest() __A : List[str] = torch.randn(2 , 3 ) __A : Tuple = test_model(x + 1 ) __A : List[str] = test_model(x + 2 ) __A : int = PreForwardHook() add_hook_to_module(__A , __A ) __A : Union[str, Any] = test_model(__A ) self.assertTrue(torch.allclose(__A , __A , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain __A : Dict = PreForwardHook() add_hook_to_module(__A , __A ) __A : Union[str, Any] = test_model(__A ) self.assertTrue(torch.allclose(__A , __A , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks __A : List[Any] = SequentialHook(PreForwardHook() , PreForwardHook() ) add_hook_to_module(__A , __A ) __A : List[str] = test_model(__A ) assert torch.allclose(__A , __A , atol=1e-5 ) def lowerCAmelCase_ ( self : Dict ): __A : Any = ModelForTest() __A : List[str] = torch.randn(2 , 3 ) __A : Union[str, Any] = test_model(__A ) __A : Dict = PostForwardHook() add_hook_to_module(__A , __A ) __A : int = test_model(__A ) self.assertTrue(torch.allclose(__A , output + 1 , atol=1e-5 ) ) # Attaching a hook to a model when it already has one replaces, does not chain __A : Optional[int] = PostForwardHook() add_hook_to_module(__A , __A ) __A : int = test_model(__A ) self.assertTrue(torch.allclose(__A , output + 1 , atol=1e-5 ) ) # You need to use the sequential hook to chain two or more hooks __A : Dict = SequentialHook(PostForwardHook() , PostForwardHook() ) add_hook_to_module(__A , __A ) __A : Union[str, Any] = test_model(__A ) assert torch.allclose(__A , output + 2 , atol=1e-5 ) def lowerCAmelCase_ ( self : Tuple ): __A : Optional[Any] = ModelForTest() __A : List[Any] = torch.randn(2 , 3 ) __A : int = test_model(__A ) __A : Tuple = PostForwardHook() add_hook_to_module(__A , __A ) __A : List[Any] = test_model(__A ) self.assertTrue(torch.allclose(__A , output + 1 ) ) self.assertTrue(outputa.requires_grad ) __A : int = True __A : Any = test_model(__A ) self.assertFalse(outputa.requires_grad ) @require_multi_gpu def lowerCAmelCase_ ( self : str ): __A : Union[str, Any] = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(execution_device=0 ) ) add_hook_to_module(model.lineara , AlignDevicesHook(execution_device=1 ) ) self.assertEqual(model.lineara.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.weight.device , torch.device(0 ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device(0 ) ) self.assertEqual(model.lineara.weight.device , torch.device(1 ) ) # We can still make a forward pass. The input does not need to be on any particular device __A : Tuple = torch.randn(2 , 3 ) __A : Tuple = model(__A ) self.assertEqual(output.device , torch.device(1 ) ) # We can add a general hook to put back output on same device as input. add_hook_to_module(__A , AlignDevicesHook(io_same_device=__A ) ) __A : List[str] = torch.randn(2 , 3 ).to(0 ) __A : Tuple = model(__A ) self.assertEqual(output.device , torch.device(0 ) ) def lowerCAmelCase_ ( self : Any ): __A : str = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __A : Optional[int] = {"""execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True} add_hook_to_module(model.lineara , AlignDevicesHook(**__A ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__A ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__A ) ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __A : List[str] = torch.device(hook_kwargs["""execution_device"""] ) self.assertEqual(model.batchnorm.running_mean.device , __A ) __A : Optional[Any] = torch.randn(2 , 3 ) __A : Optional[int] = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload __A : str = { """execution_device""": 0 if torch.cuda.is_available() else """cpu""", """offload""": True, """offload_buffers""": True, } add_hook_to_module(model.lineara , AlignDevicesHook(**__A ) ) add_hook_to_module(model.batchnorm , AlignDevicesHook(**__A ) ) add_hook_to_module(model.lineara , AlignDevicesHook(**__A ) ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __A : int = torch.randn(2 , 3 ) __A : Optional[Any] = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_module(model.lineara ) remove_hook_from_module(model.batchnorm ) remove_hook_from_module(model.lineara ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def lowerCAmelCase_ ( self : List[str] ): __A : Dict = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __A : str = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook(__A , execution_device=__A , offload=__A ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __A : List[Any] = torch.device(__A ) self.assertEqual(model.batchnorm.running_mean.device , __A ) __A : List[str] = torch.randn(2 , 3 ) __A : Dict = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__A ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook(__A , execution_device=__A , offload=__A , offload_buffers=__A ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __A : Dict = torch.randn(2 , 3 ) __A : List[str] = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__A ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) def lowerCAmelCase_ ( self : Optional[int] ): __A : Any = ModelForTest() # Everything is on CPU self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # This will move each submodule on different devices __A : int = 0 if torch.cuda.is_available() else """cpu""" attach_align_device_hook( __A , execution_device=__A , offload=__A , weights_map=model.state_dict() ) # Parameters have been offloaded, so on the meta device self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) # Buffers are not included in the offload by default, so are on the execution device __A : Optional[int] = torch.device(__A ) self.assertEqual(model.batchnorm.running_mean.device , __A ) __A : Optional[Any] = torch.randn(2 , 3 ) __A : Any = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__A ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) # Now test with buffers included in the offload attach_align_device_hook( __A , execution_device=__A , offload=__A , weights_map=model.state_dict() , offload_buffers=__A , ) # Parameters have been offloaded, so on the meta device, buffers included self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""meta""" ) ) self.assertEqual(model.batchnorm.running_mean.device , torch.device("""meta""" ) ) __A : Any = torch.randn(2 , 3 ) __A : int = model(__A ) self.assertEqual(output.device , __A ) # Removing hooks loads back the weights in the model. remove_hook_from_submodules(__A ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.batchnorm.weight.device , torch.device("""cpu""" ) ) self.assertEqual(model.lineara.weight.device , torch.device("""cpu""" ) )
17
from math import sqrt def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0_0_0 ): __snake_case : int = 0 __snake_case : int = 0 __snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__lowerCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
81
0
'''simple docstring''' import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets _SCREAMING_SNAKE_CASE = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" _SCREAMING_SNAKE_CASE = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" _SCREAMING_SNAKE_CASE = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def _snake_case ( self ) -> Union[str, Any]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/krishnap25/mauve" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/krishnap25/mauve"] , reference_urls=[ "https://arxiv.org/abs/2102.01454", "https://github.com/krishnap25/mauve", ] , ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase=None , _lowerCAmelCase="auto" , _lowerCAmelCase=-1 , _lowerCAmelCase=0.9 , _lowerCAmelCase=5 , _lowerCAmelCase=500 , _lowerCAmelCase="gpt2-large" , _lowerCAmelCase=-1 , _lowerCAmelCase=1024 , _lowerCAmelCase=25 , _lowerCAmelCase=5 , _lowerCAmelCase=True , _lowerCAmelCase=25 , ) -> Optional[int]: _lowerCAmelCase = compute_mauve( p_text=_lowerCAmelCase , q_text=_lowerCAmelCase , p_features=_lowerCAmelCase , q_features=_lowerCAmelCase , p_tokens=_lowerCAmelCase , q_tokens=_lowerCAmelCase , num_buckets=_lowerCAmelCase , pca_max_data=_lowerCAmelCase , kmeans_explained_var=_lowerCAmelCase , kmeans_num_redo=_lowerCAmelCase , kmeans_max_iter=_lowerCAmelCase , featurize_model_name=_lowerCAmelCase , device_id=_lowerCAmelCase , max_text_length=_lowerCAmelCase , divergence_curve_discretization_size=_lowerCAmelCase , mauve_scaling_factor=_lowerCAmelCase , verbose=_lowerCAmelCase , seed=_lowerCAmelCase , ) return out
18
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class a (_lowerCAmelCase ): """simple docstring""" def __snake_case ( self : str ) -> str: __snake_case : Tuple = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "neck_hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) ) class a : """simple docstring""" def __init__( self : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Tuple=13 , lowerCamelCase : str=32 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=3 , lowerCamelCase : Any=640 , lowerCamelCase : Optional[Any]=4 , lowerCamelCase : Tuple="silu" , lowerCamelCase : int=3 , lowerCamelCase : Dict=32 , lowerCamelCase : str=0.1 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=0.02 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=10 , lowerCamelCase : int=None , ) -> str: __snake_case : Optional[Any] = parent __snake_case : Optional[Any] = batch_size __snake_case : Any = image_size __snake_case : List[Any] = patch_size __snake_case : Any = num_channels __snake_case : Union[str, Any] = last_hidden_size __snake_case : Any = num_attention_heads __snake_case : Any = hidden_act __snake_case : Tuple = conv_kernel_size __snake_case : Any = output_stride __snake_case : Any = hidden_dropout_prob __snake_case : List[Any] = attention_probs_dropout_prob __snake_case : Optional[Any] = classifier_dropout_prob __snake_case : Union[str, Any] = use_labels __snake_case : Optional[int] = is_training __snake_case : Dict = num_labels __snake_case : Any = initializer_range __snake_case : Optional[int] = scope def __snake_case ( self : str ) -> Union[str, Any]: __snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __snake_case : List[Any] = None __snake_case : Optional[int] = None if self.use_labels: __snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels ) __snake_case : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __snake_case : Optional[Any] = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case ( self : Any ) -> Union[str, Any]: return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] ) -> Dict: __snake_case : List[Any] = MobileViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[str] = model(lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ) -> List[str]: __snake_case : str = self.num_labels __snake_case : List[Any] = MobileViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Dict: __snake_case : Union[str, Any] = self.num_labels __snake_case : Optional[int] = MobileViTForSemanticSegmentation(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __snake_case : Tuple = model(lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) __snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case ( self : Optional[int] ) -> List[Any]: __snake_case : Optional[Any] = self.prepare_config_and_inputs() __snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = config_and_inputs __snake_case : Dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) __UpperCAmelCase : Optional[Any] = ( { "feature-extraction": MobileViTModel, "image-classification": MobileViTForImageClassification, "image-segmentation": MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCAmelCase : List[str] = False __UpperCAmelCase : int = False __UpperCAmelCase : Optional[int] = False __UpperCAmelCase : Optional[int] = False def __snake_case ( self : Optional[int] ) -> Dict: __snake_case : Tuple = MobileViTModelTester(self ) __snake_case : Any = MobileViTConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def __snake_case ( self : Optional[int] ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason="MobileViT does not use inputs_embeds" ) def __snake_case ( self : Dict ) -> Any: pass @unittest.skip(reason="MobileViT does not support input and output embeddings" ) def __snake_case ( self : Dict ) -> List[Any]: pass @unittest.skip(reason="MobileViT does not output attentions" ) def __snake_case ( self : int ) -> Dict: pass def __snake_case ( self : int ) -> Union[str, Any]: __snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : Optional[Any] = model_class(lowerCamelCase ) __snake_case : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __snake_case : int = [*signature.parameters.keys()] __snake_case : List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __snake_case ( self : int ) -> Tuple: pass def __snake_case ( self : Any ) -> Tuple: __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def __snake_case ( self : Any ) -> str: def check_hidden_states_output(lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any ): __snake_case : int = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __snake_case : int = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __snake_case : Union[str, Any] = outputs.hidden_states __snake_case : int = 5 self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. __snake_case : List[Any] = 2 for i in range(len(lowerCamelCase ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) __snake_case , __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __snake_case : str = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __snake_case : List[Any] = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def __snake_case ( self : Any ) -> Any: __snake_case : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) def __snake_case ( self : List[str] ) -> List[str]: __snake_case : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase ) @slow def __snake_case ( self : List[str] ) -> Any: for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __snake_case : List[str] = MobileViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def lowerCAmelCase_ ( ): __snake_case : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class a (unittest.TestCase ): """simple docstring""" @cached_property def __snake_case ( self : str ) -> Dict: return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None @slow def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : Tuple = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowerCamelCase ) __snake_case : Optional[Any] = self.default_image_processor __snake_case : Union[str, Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Dict = model(**lowerCamelCase ) # verify the logits __snake_case : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : str ) -> Optional[int]: __snake_case : Optional[int] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : str = model.to(lowerCamelCase ) __snake_case : int = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Optional[int] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : List[str] = model(**lowerCamelCase ) __snake_case : Union[str, Any] = outputs.logits # verify the logits __snake_case : Tuple = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , lowerCamelCase ) __snake_case : Union[str, Any] = torch.tensor( [ [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]], [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]], [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]], ] , device=lowerCamelCase , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def __snake_case ( self : Union[str, Any] ) -> Optional[int]: __snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : Tuple = model.to(lowerCamelCase ) __snake_case : Dict = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" ) __snake_case : List[Any] = prepare_img() __snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __snake_case : Any = model(**lowerCamelCase ) __snake_case : Dict = outputs.logits.detach().cpu() __snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(50, 60)] ) __snake_case : int = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , lowerCamelCase ) __snake_case : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ) __snake_case : Optional[int] = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , lowerCamelCase )
81
0
"""simple docstring""" import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class _UpperCAmelCase( unittest.TestCase , lowerCamelCase ): def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = load_tool('''text-classification''') self.tool.setup() _UpperCamelCase = load_tool('''text-classification''' , remote=__a) def UpperCAmelCase ( self) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.tool('''That\'s quite cool''' , ['''positive''', '''negative''']) self.assertEqual(__a , '''positive''') def UpperCAmelCase ( self) -> int: '''simple docstring''' _UpperCamelCase = self.remote_tool('''That\'s quite cool''' , ['''positive''', '''negative''']) self.assertEqual(__a , '''positive''') def UpperCAmelCase ( self) -> Dict: '''simple docstring''' _UpperCamelCase = self.tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative''']) self.assertEqual(__a , '''positive''') def UpperCAmelCase ( self) -> Optional[Any]: '''simple docstring''' _UpperCamelCase = self.remote_tool(text='''That\'s quite cool''' , labels=['''positive''', '''negative''']) self.assertEqual(__a , '''positive''')
19
import warnings from ...utils import logging from .image_processing_imagegpt import ImageGPTImageProcessor _snake_case : int = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[int] , *lowerCamelCase : List[Any] , **lowerCamelCase : int ) -> None: warnings.warn( "The class ImageGPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use ImageGPTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
0
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() _lowerCAmelCase: List[str] = logging.get_logger() def _lowercase( __a : int , __a : str , __a : LevitConfig , __a : Path , __a : bool = True ): print(f"""Converting {name}...""" ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": a__ =timm.create_model('levit_128s' , pretrained=__a ) else: a__ =timm.create_model('levit_128' , pretrained=__a ) if hidden_sizes == 192: a__ =timm.create_model('levit_192' , pretrained=__a ) if hidden_sizes == 256: a__ =timm.create_model('levit_256' , pretrained=__a ) if hidden_sizes == 384: a__ =timm.create_model('levit_384' , pretrained=__a ) from_model.eval() a__ =LevitForImageClassificationWithTeacher(__a ).eval() a__ =OrderedDict() a__ =from_model.state_dict() a__ =list(from_model.state_dict().keys() ) a__ =list(our_model.state_dict().keys() ) print(len(__a ) , len(__a ) ) for i in range(len(__a ) ): a__ =weights[og_keys[i]] our_model.load_state_dict(__a ) a__ =torch.randn((2, 3, 224, 224) ) a__ =from_model(__a ) a__ =our_model(__a ).logits assert torch.allclose(__a , __a ), "The model logits don't match the original one." a__ =name print(__a ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) a__ =LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f"""Pushed {checkpoint_name}""" ) def _lowercase( __a : Path , __a : str = None , __a : bool = True ): a__ ='imagenet-1k-id2label.json' a__ =1000 a__ =(1, num_labels) a__ ='huggingface/label-files' a__ =num_labels a__ =json.load(open(hf_hub_download(__a , __a , repo_type='dataset' ) , 'r' ) ) a__ ={int(__a ): v for k, v in idalabel.items()} a__ =idalabel a__ ={v: k for k, v in idalabel.items()} a__ =partial(__a , num_labels=__a , idalabel=__a , labelaid=__a ) a__ ={ 'levit-128S': 128, 'levit-128': 128, 'levit-192': 192, 'levit-256': 256, 'levit-384': 384, } a__ ={ '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] , __a , names_to_config[model_name] , __a , __a ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , __a , __a , __a , __a ) return config, expected_shape if __name__ == "__main__": _lowerCAmelCase: 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 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', ) _lowerCAmelCase: Union[str, Any] = parser.parse_args() _lowerCAmelCase: 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)
20
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 _snake_case : Optional[Any] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[str] = ["pixel_values"] def __init__( self : List[Any] , lowerCamelCase : bool = True , lowerCamelCase : Union[int, float] = 1 / 255 , lowerCamelCase : bool = True , lowerCamelCase : int = 8 , **lowerCamelCase : Tuple , ) -> None: super().__init__(**lowerCamelCase ) __snake_case : Dict = do_rescale __snake_case : Dict = rescale_factor __snake_case : Optional[Any] = do_pad __snake_case : Tuple = pad_size def __snake_case ( self : Dict , lowerCamelCase : np.ndarray , lowerCamelCase : float , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase : Optional[int] ) -> np.ndarray: return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def __snake_case ( self : Optional[Any] , lowerCamelCase : np.ndarray , lowerCamelCase : int , lowerCamelCase : Optional[Union[str, ChannelDimension]] = None ) -> Tuple: __snake_case , __snake_case : List[str] = get_image_size(lowerCamelCase ) __snake_case : Optional[Any] = (old_height // size + 1) * size - old_height __snake_case : List[Any] = (old_width // size + 1) * size - old_width return pad(lowerCamelCase , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCamelCase ) def __snake_case ( self : Tuple , lowerCamelCase : ImageInput , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[float] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[int] = None , lowerCamelCase : Optional[Union[str, TensorType]] = None , lowerCamelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **lowerCamelCase : Union[str, Any] , ) -> List[str]: __snake_case : int = do_rescale if do_rescale is not None else self.do_rescale __snake_case : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case : str = do_pad if do_pad is not None else self.do_pad __snake_case : Any = pad_size if pad_size is not None else self.pad_size __snake_case : int = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. __snake_case : str = [to_numpy_array(lowerCamelCase ) for image in images] if do_rescale: __snake_case : Optional[int] = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_pad: __snake_case : Optional[Any] = [self.pad(lowerCamelCase , size=lowerCamelCase ) for image in images] __snake_case : int = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __snake_case : Union[str, Any] = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
81
0
def lowerCAmelCase_ ( lowerCamelCase = 1000 ): __magic_name__ : Optional[int] =-1 __magic_name__ : Tuple =0 for a in range(1 , n // 3 ): # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c __magic_name__ : str =(n * n - 2 * a * n) // (2 * n - 2 * a) __magic_name__ : Tuple =n - a - b if c * c == (a * a + b * b): __magic_name__ : Any =a * b * c if candidate >= product: __magic_name__ : Optional[int] =candidate return product if __name__ == "__main__": print(F"""{solution() = }""")
21
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _snake_case : Any = { "configuration_informer": [ "INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "InformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "InformerForPrediction", "InformerModel", "InformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys _snake_case : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
0
'''simple docstring''' import numpy as np from PIL import Image def snake_case_ (UpperCamelCase : np.ndarray , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' _a = np.array(UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input array is not a square matrix''' ) _a = 0 _a = 0 _a = 0 _a = 0 # compute the shape of the output matrix _a = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape _a = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix _a = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _a = 0 _a = 0 return updated_arr def snake_case_ (UpperCamelCase : np.ndarray , UpperCamelCase : int , UpperCamelCase : int ): '''simple docstring''' _a = np.array(UpperCamelCase ) if arr.shape[0] != arr.shape[1]: raise ValueError('''The input array is not a square matrix''' ) _a = 0 _a = 0 _a = 0 _a = 0 # compute the shape of the output matrix _a = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape _a = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix _a = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 _a = 0 _a = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image _snake_case : str = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
22
from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging _snake_case : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[Any] , lowerCamelCase : CLIPSegForImageSegmentation , lowerCamelCase : CLIPSegProcessor , lowerCamelCase : AutoencoderKL , lowerCamelCase : CLIPTextModel , lowerCamelCase : CLIPTokenizer , lowerCamelCase : UNetaDConditionModel , lowerCamelCase : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , lowerCamelCase : StableDiffusionSafetyChecker , lowerCamelCase : CLIPImageProcessor , ) -> Tuple: super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: __snake_case : Tuple = ( F'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`' F' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure ' "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : Any = dict(scheduler.config ) __snake_case : List[Any] = 1 __snake_case : Tuple = FrozenDict(lowerCamelCase ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: __snake_case : List[str] = ( F'The configuration file of this scheduler: {scheduler} has not set the configuration' " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __snake_case : List[str] = dict(scheduler.config ) __snake_case : List[str] = True __snake_case : Any = FrozenDict(lowerCamelCase ) if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=lowerCamelCase , segmentation_processor=lowerCamelCase , vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , ) def __snake_case ( self : Dict , lowerCamelCase : Optional[Union[str, int]] = "auto" ) -> Tuple: if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __snake_case : Any = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def __snake_case ( self : List[Any] ) -> Any: self.enable_attention_slicing(lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> str: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) __snake_case : Optional[int] = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(lowerCamelCase , lowerCamelCase ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __snake_case ( self : int ) -> Any: if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(lowerCamelCase , "_hf_hook" ) and hasattr(module._hf_hook , "execution_device" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() def __call__( self : List[Any] , lowerCamelCase : Union[str, List[str]] , lowerCamelCase : Union[torch.FloatTensor, PIL.Image.Image] , lowerCamelCase : str , lowerCamelCase : int = 512 , lowerCamelCase : int = 512 , lowerCamelCase : int = 50 , lowerCamelCase : float = 7.5 , lowerCamelCase : Optional[Union[str, List[str]]] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : float = 0.0 , lowerCamelCase : Optional[torch.Generator] = None , lowerCamelCase : Optional[torch.FloatTensor] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , lowerCamelCase : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , lowerCamelCase : int = 1 , **lowerCamelCase : Dict , ) -> List[str]: __snake_case : Tuple = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) __snake_case : str = self.segmentation_model(**lowerCamelCase ) __snake_case : Dict = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() __snake_case : List[Any] = self.numpy_to_pil(lowerCamelCase )[0].resize(image.size ) # Run inpainting pipeline with the generated mask __snake_case : Tuple = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=lowerCamelCase , image=lowerCamelCase , mask_image=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , )
81
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) snake_case__ : Optional[int] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys snake_case__ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
23
class a : """simple docstring""" def __init__( self : Tuple , lowerCamelCase : list ) -> None: __snake_case : str = set_counts __snake_case : Union[str, Any] = max(lowerCamelCase ) __snake_case : List[Any] = len(lowerCamelCase ) __snake_case : Tuple = [1] * num_sets __snake_case : Dict = list(range(lowerCamelCase ) ) def __snake_case ( self : str , lowerCamelCase : int , lowerCamelCase : int ) -> bool: __snake_case : List[Any] = self.get_parent(lowerCamelCase ) __snake_case : Tuple = self.get_parent(lowerCamelCase ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] __snake_case : List[str] = 0 __snake_case : List[Any] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 __snake_case : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] __snake_case : Union[str, Any] = 0 __snake_case : Optional[int] = src_parent __snake_case : Tuple = self.set_counts[src_parent] __snake_case : str = max(self.max_set , lowerCamelCase ) return True def __snake_case ( self : int , lowerCamelCase : int ) -> int: if self.parents[disj_set] == disj_set: return disj_set __snake_case : Optional[int] = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
81
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCAmelCase_ : Optional[Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = { '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase): __lowercase : str = '''resnet''' __lowercase : Optional[int] = ['''basic''', '''bottleneck'''] def __init__( self , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=64 , __SCREAMING_SNAKE_CASE=[256, 512, 1024, 2048] , __SCREAMING_SNAKE_CASE=[3, 4, 6, 3] , __SCREAMING_SNAKE_CASE="bottleneck" , __SCREAMING_SNAKE_CASE="relu" , __SCREAMING_SNAKE_CASE=False , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=None , **__SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {",".join(self.layer_types )}''' ) __snake_case = num_channels __snake_case = embedding_size __snake_case = hidden_sizes __snake_case = depths __snake_case = layer_type __snake_case = hidden_act __snake_case = downsample_in_first_stage __snake_case = ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(__SCREAMING_SNAKE_CASE ) + 1 )] __snake_case , __snake_case = get_aligned_output_features_output_indices( out_features=__SCREAMING_SNAKE_CASE , out_indices=__SCREAMING_SNAKE_CASE , stage_names=self.stage_names ) class lowerCAmelCase ( __lowerCAmelCase): __lowercase : List[Any] = version.parse('''1.11''') @property def lowerCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCAmelCase ( self ) -> float: '''simple docstring''' return 1E-3
24
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class a (unittest.TestCase ): """simple docstring""" def __init__( self : int , lowerCamelCase : Any , lowerCamelCase : int=7 , lowerCamelCase : str=3 , lowerCamelCase : Optional[int]=30 , lowerCamelCase : Dict=400 , lowerCamelCase : str=True , lowerCamelCase : str=None , lowerCamelCase : Any=True , lowerCamelCase : Union[str, Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[Any]=[0.5, 0.5, 0.5] , lowerCamelCase : List[str]=True , lowerCamelCase : Optional[int]=1 / 255 , lowerCamelCase : Any=True , ) -> str: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __snake_case : Optional[Any] = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __snake_case : Optional[Any] = parent __snake_case : List[Any] = batch_size __snake_case : Optional[int] = num_channels __snake_case : str = min_resolution __snake_case : int = max_resolution __snake_case : int = do_resize __snake_case : Tuple = size __snake_case : Any = do_normalize __snake_case : int = image_mean __snake_case : Tuple = image_std __snake_case : Dict = do_rescale __snake_case : Optional[Any] = rescale_factor __snake_case : str = do_pad def __snake_case ( self : Any ) -> int: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __snake_case ( self : Dict , lowerCamelCase : List[Any] , lowerCamelCase : Optional[Any]=False ) -> List[str]: if not batched: __snake_case : Dict = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __snake_case , __snake_case : Dict = image.size else: __snake_case , __snake_case : List[str] = image.shape[1], image.shape[2] if w < h: __snake_case : Optional[int] = int(self.size["shortest_edge"] * h / w ) __snake_case : int = self.size["shortest_edge"] elif w > h: __snake_case : List[str] = self.size["shortest_edge"] __snake_case : Optional[Any] = int(self.size["shortest_edge"] * w / h ) else: __snake_case : List[Any] = self.size["shortest_edge"] __snake_case : Any = self.size["shortest_edge"] else: __snake_case : int = [] for image in image_inputs: __snake_case , __snake_case : List[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __snake_case : str = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a (_lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = ConditionalDetrImageProcessor if is_vision_available() else None def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : Optional[Any] = ConditionalDetrImageProcessingTester(self ) @property def __snake_case ( self : Any ) -> str: return self.image_processor_tester.prepare_image_processor_dict() def __snake_case ( self : Optional[Any] ) -> Optional[int]: __snake_case : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase , "image_mean" ) ) self.assertTrue(hasattr(lowerCamelCase , "image_std" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_normalize" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_resize" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def __snake_case ( self : Any ) -> Dict: __snake_case : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1333} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) __snake_case : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def __snake_case ( self : Optional[Any] ) -> Dict: pass def __snake_case ( self : Tuple ) -> str: # Initialize image_processing __snake_case : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , Image.Image ) # Test not batched input __snake_case : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __snake_case : Dict = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> str: # Initialize image_processing __snake_case : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __snake_case : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , numpify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , np.ndarray ) # Test not batched input __snake_case : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : List[Any] = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Optional[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __snake_case ( self : int ) -> List[str]: # Initialize image_processing __snake_case : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __snake_case : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase , torchify=lowerCamelCase ) for image in image_inputs: self.assertIsInstance(lowerCamelCase , torch.Tensor ) # Test not batched input __snake_case : Optional[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values __snake_case , __snake_case : List[Any] = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __snake_case : int = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __snake_case , __snake_case : Union[str, Any] = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __snake_case ( self : Any ) -> Optional[int]: # prepare image and target __snake_case : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : List[Any] = {"image_id": 39769, "annotations": target} # encode them __snake_case : List[str] = ConditionalDetrImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50" ) __snake_case : List[str] = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : Tuple = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Optional[int] = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : List[Any] = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : Optional[int] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : List[Any] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Optional[Any] = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : Dict = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __snake_case : int = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Tuple = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def __snake_case ( self : str ) -> Tuple: # prepare image, target and masks_path __snake_case : Optional[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: __snake_case : str = json.loads(f.read() ) __snake_case : str = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target} __snake_case : Optional[int] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __snake_case : int = ConditionalDetrImageProcessor(format="coco_panoptic" ) __snake_case : str = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __snake_case : List[str] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __snake_case : Dict = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __snake_case : Any = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , lowerCamelCase ) ) # verify boxes __snake_case : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __snake_case : Optional[Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __snake_case : Tuple = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __snake_case : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __snake_case : int = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __snake_case : List[Any] = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __snake_case : List[str] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __snake_case : Any = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
81
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a_ = logging.get_logger(__name__) a_ = { 'microsoft/swin-tiny-patch4-window7-224': ( 'https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json' ), # See all Swin models at https://huggingface.co/models?filter=swin } class _UpperCamelCase ( __A , __A ): '''simple docstring''' lowerCamelCase__ ='swin' lowerCamelCase__ ={ 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Union[str, Any] , a : Tuple=224 , a : Optional[Any]=4 , a : Optional[Any]=3 , a : Optional[Any]=96 , a : Union[str, Any]=[2, 2, 6, 2] , a : Tuple=[3, 6, 12, 24] , a : Union[str, Any]=7 , a : List[str]=4.0 , a : Optional[Any]=True , a : Union[str, Any]=0.0 , a : Optional[int]=0.0 , a : Union[str, Any]=0.1 , a : List[Any]="gelu" , a : Union[str, Any]=False , a : Any=0.02 , a : str=1e-5 , a : Any=32 , a : Optional[int]=None , a : str=None , **a : Dict , ) -> Any: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : int = image_size SCREAMING_SNAKE_CASE : Any = patch_size SCREAMING_SNAKE_CASE : Optional[Any] = num_channels SCREAMING_SNAKE_CASE : Any = embed_dim SCREAMING_SNAKE_CASE : List[str] = depths SCREAMING_SNAKE_CASE : Union[str, Any] = len(a ) SCREAMING_SNAKE_CASE : Dict = num_heads SCREAMING_SNAKE_CASE : Optional[int] = window_size SCREAMING_SNAKE_CASE : List[Any] = mlp_ratio SCREAMING_SNAKE_CASE : int = qkv_bias SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = drop_path_rate SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : int = use_absolute_embeddings SCREAMING_SNAKE_CASE : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Tuple = encoder_stride # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE : int = int(embed_dim * 2 ** (len(a ) - 1) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["stem"] + [F"stage{idx}" for idx in range(1 , len(a ) + 1 )] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = get_aligned_output_features_output_indices( out_features=a , out_indices=a , stage_names=self.stage_names ) class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =version.parse('1.11' ) @property def __UpperCamelCase ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def __UpperCamelCase ( self : Optional[int] ) -> float: """simple docstring""" return 1e-4
25
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig _snake_case : Optional[Any] = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring _snake_case : Dict = "UperNetConfig" class a (nn.Module ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : Union[int, Tuple[int, int]] , lowerCamelCase : Union[int, Tuple[int, int], str] = 0 , lowerCamelCase : bool = False , lowerCamelCase : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() __snake_case : Union[str, Any] = nn.Convad( in_channels=lowerCamelCase , out_channels=lowerCamelCase , kernel_size=lowerCamelCase , padding=lowerCamelCase , bias=lowerCamelCase , dilation=lowerCamelCase , ) __snake_case : Dict = nn.BatchNormad(lowerCamelCase ) __snake_case : List[Any] = nn.ReLU() def __snake_case ( self : List[Any] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : Dict = self.conv(lowerCamelCase ) __snake_case : int = self.batch_norm(lowerCamelCase ) __snake_case : Optional[Any] = self.activation(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : str , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : int ) -> None: super().__init__() __snake_case : Tuple = [ nn.AdaptiveAvgPoolad(lowerCamelCase ), UperNetConvModule(lowerCamelCase , lowerCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : Dict , lowerCamelCase : torch.Tensor ) -> torch.Tensor: __snake_case : List[str] = input for layer in self.layers: __snake_case : Tuple = layer(lowerCamelCase ) return hidden_state class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Tuple[int, ...] , lowerCamelCase : int , lowerCamelCase : int , lowerCamelCase : bool ) -> None: super().__init__() __snake_case : Dict = pool_scales __snake_case : List[str] = align_corners __snake_case : List[Any] = in_channels __snake_case : str = channels __snake_case : Optional[Any] = [] for i, pool_scale in enumerate(lowerCamelCase ): __snake_case : Union[str, Any] = UperNetPyramidPoolingBlock(pool_scale=lowerCamelCase , in_channels=lowerCamelCase , channels=lowerCamelCase ) self.blocks.append(lowerCamelCase ) self.add_module(str(lowerCamelCase ) , lowerCamelCase ) def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> List[torch.Tensor]: __snake_case : Tuple = [] for ppm in self.blocks: __snake_case : Any = ppm(lowerCamelCase ) __snake_case : List[Any] = nn.functional.interpolate( lowerCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(lowerCamelCase ) return ppm_outs class a (nn.Module ): """simple docstring""" def __init__( self : int , lowerCamelCase : str , lowerCamelCase : str ) -> List[str]: super().__init__() __snake_case : Dict = config __snake_case : List[str] = config.pool_scales # e.g. (1, 2, 3, 6) __snake_case : Tuple = in_channels __snake_case : str = config.hidden_size __snake_case : List[str] = False __snake_case : Any = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module __snake_case : Tuple = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) __snake_case : List[str] = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module __snake_case : List[Any] = nn.ModuleList() __snake_case : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer __snake_case : Union[str, Any] = UperNetConvModule(lowerCamelCase , self.channels , kernel_size=1 ) __snake_case : Optional[int] = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(lowerCamelCase ) self.fpn_convs.append(lowerCamelCase ) __snake_case : int = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def __snake_case ( self : List[str] ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> str: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : List[Any] , lowerCamelCase : Tuple ) -> Optional[int]: __snake_case : str = inputs[-1] __snake_case : int = [x] psp_outs.extend(self.psp_modules(lowerCamelCase ) ) __snake_case : Tuple = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Union[str, Any] = self.bottleneck(lowerCamelCase ) return output def __snake_case ( self : int , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # build laterals __snake_case : Any = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(lowerCamelCase ) ) # build top-down path __snake_case : Dict = len(lowerCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Union[str, Any] = laterals[i - 1].shape[2:] __snake_case : Optional[int] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=lowerCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs __snake_case : str = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): __snake_case : Tuple = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) __snake_case : str = torch.cat(lowerCamelCase , dim=1 ) __snake_case : Optional[Any] = self.fpn_bottleneck(lowerCamelCase ) __snake_case : Tuple = self.classifier(lowerCamelCase ) return output class a (nn.Module ): """simple docstring""" def __init__( self : Any , lowerCamelCase : Optional[int] , lowerCamelCase : int = 2 , lowerCamelCase : int = 3 , lowerCamelCase : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() __snake_case : List[Any] = config __snake_case : List[str] = config.auxiliary_in_channels __snake_case : List[Any] = config.auxiliary_channels __snake_case : Tuple = config.auxiliary_num_convs __snake_case : int = config.auxiliary_concat_input __snake_case : Optional[int] = in_index __snake_case : Tuple = (kernel_size // 2) * dilation __snake_case : Optional[int] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=lowerCamelCase , padding=lowerCamelCase , dilation=lowerCamelCase ) ) if self.num_convs == 0: __snake_case : Union[str, Any] = nn.Identity() else: __snake_case : Any = nn.Sequential(*lowerCamelCase ) if self.concat_input: __snake_case : int = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=lowerCamelCase , padding=kernel_size // 2 ) __snake_case : Optional[Any] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def __snake_case ( self : Dict ) -> Optional[Any]: self.apply(self._init_weights ) def __snake_case ( self : Tuple , lowerCamelCase : Tuple ) -> Optional[int]: if isinstance(lowerCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def __snake_case ( self : Optional[int] , lowerCamelCase : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps __snake_case : List[str] = encoder_hidden_states[self.in_index] __snake_case : Optional[Any] = self.convs(lowerCamelCase ) if self.concat_input: __snake_case : Optional[Any] = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) __snake_case : Union[str, Any] = self.classifier(lowerCamelCase ) return output class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = UperNetConfig __UpperCAmelCase : int = "pixel_values" __UpperCAmelCase : str = True def __snake_case ( self : Union[str, Any] , lowerCamelCase : List[Any] ) -> List[Any]: if isinstance(lowerCamelCase , lowerCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def __snake_case ( self : Optional[Any] ) -> List[str]: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def __snake_case ( self : List[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[Any]=False ) -> Dict: if isinstance(lowerCamelCase , lowerCamelCase ): __snake_case : Union[str, Any] = value _snake_case : Dict = R"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _snake_case : Tuple = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( "UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes." , _lowerCAmelCase , ) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Dict , lowerCamelCase : int ) -> Optional[int]: super().__init__(lowerCamelCase ) __snake_case : Any = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) __snake_case : Union[str, Any] = UperNetHead(lowerCamelCase , in_channels=self.backbone.channels ) __snake_case : Any = UperNetFCNHead(lowerCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def __snake_case ( self : Union[str, Any] , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[bool] = None , lowerCamelCase : Optional[torch.Tensor] = None , lowerCamelCase : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: __snake_case : Any = return_dict if return_dict is not None else self.config.use_return_dict __snake_case : int = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __snake_case : str = output_attentions if output_attentions is not None else self.config.output_attentions __snake_case : Tuple = self.backbone.forward_with_filtered_kwargs( lowerCamelCase , output_hidden_states=lowerCamelCase , output_attentions=lowerCamelCase ) __snake_case : List[Any] = outputs.feature_maps __snake_case : List[Any] = self.decode_head(lowerCamelCase ) __snake_case : List[str] = nn.functional.interpolate(lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : Optional[int] = None if self.auxiliary_head is not None: __snake_case : Dict = self.auxiliary_head(lowerCamelCase ) __snake_case : Dict = nn.functional.interpolate( lowerCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=lowerCamelCase ) __snake_case : int = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss __snake_case : Any = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) __snake_case : Union[str, Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = loss_fct(lowerCamelCase , lowerCamelCase ) __snake_case : Optional[Any] = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: __snake_case : Any = (logits,) + outputs[1:] else: __snake_case : str = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
81
0
'''simple docstring''' import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home __UpperCamelCase = HUGGINGFACE_HUB_CACHE __UpperCamelCase = "config.json" __UpperCamelCase = "diffusion_pytorch_model.bin" __UpperCamelCase = "diffusion_flax_model.msgpack" __UpperCamelCase = "model.onnx" __UpperCamelCase = "diffusion_pytorch_model.safetensors" __UpperCamelCase = "weights.pb" __UpperCamelCase = "https://huggingface.co" __UpperCamelCase = default_cache_path __UpperCamelCase = "diffusers_modules" __UpperCamelCase = os.getenv("HF_MODULES_CACHE", os.path.join(hf_cache_home, "modules")) __UpperCamelCase = ["fp16", "non-ema"] __UpperCamelCase = ".self_attn"
26
from __future__ import annotations def lowerCAmelCase_ ( __lowerCamelCase ): if not nums: return 0 __snake_case : Any = nums[0] __snake_case : str = 0 for num in nums[1:]: __snake_case , __snake_case : List[str] = ( max_excluding + num, max(__lowerCamelCase , __lowerCamelCase ), ) return max(__lowerCamelCase , __lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
81
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A : Dict = logging.get_logger(__name__) __A : List[Any] = { "junnyu/roformer_chinese_small": "https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json", "junnyu/roformer_chinese_base": "https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json", "junnyu/roformer_chinese_char_small": ( "https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json" ), "junnyu/roformer_chinese_char_base": ( "https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json" ), "junnyu/roformer_small_discriminator": ( "https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json" ), "junnyu/roformer_small_generator": ( "https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCamelCase( __snake_case ): '''simple docstring''' __magic_name__ = 'roformer' def __init__( self , snake_case_=5_0000 , snake_case_=None , snake_case_=768 , snake_case_=12 , snake_case_=12 , snake_case_=3072 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=1536 , snake_case_=2 , snake_case_=0.02 , snake_case_=1E-12 , snake_case_=0 , snake_case_=False , snake_case_=True , **snake_case_ , ): super().__init__(pad_token_id=snake_case_ , **snake_case_ ) _A = vocab_size _A = hidden_size if embedding_size is None else embedding_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = hidden_act _A = intermediate_size _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = type_vocab_size _A = initializer_range _A = layer_norm_eps _A = rotary_value _A = use_cache class lowerCamelCase( __snake_case ): '''simple docstring''' @property def lowerCAmelCase__ ( self ): if self.task == "multiple-choice": _A = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _A = {0: 'batch', 1: 'sequence'} _A = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis), ] )
27
from __future__ import annotations from typing import Any def lowerCAmelCase_ ( __lowerCamelCase ): create_state_space_tree(__lowerCamelCase , [] , 0 ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == len(__lowerCamelCase ): print(__lowerCamelCase ) return create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(__lowerCamelCase , __lowerCamelCase , index + 1 ) current_subsequence.pop() if __name__ == "__main__": _snake_case : list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["A", "B", "C"]) generate_all_subsequences(seq)
81
0
'''simple docstring''' from dataclasses import dataclass, field from typing import Optional @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be trained.'''} ) A : Optional[str] = field( default='''./''' , metadata={'''help''': '''Save dir where model repo is cloned and models updates are saved to.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path of training dataset.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) A : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size for training.'''} ) A : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size for evaluation.'''} ) A : Optional[float] = field(default=0.1 , metadata={'''help''': '''Value of weight decay.'''} ) A : Optional[int] = field( default=10_000 , metadata={'''help''': '''Size of buffer used to shuffle streaming dataset.'''} ) A : Optional[float] = field(default=2e-4 , metadata={'''help''': '''Learning rate fo training.'''} ) A : Optional[str] = field(default='''cosine''' , metadata={'''help''': '''Learning rate.'''} ) A : Optional[int] = field( default=750 , metadata={'''help''': '''Number of warmup steps in the learning rate schedule.'''} ) A : Optional[int] = field( default=16 , metadata={'''help''': '''Number of gradient accumulation steps.'''} ) A : Optional[bool] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Use gradient checkpointing to reduce memory footprint.'''} ) A : Optional[int] = field(default=50_000 , metadata={'''help''': '''Maximum number of training steps.'''} ) A : Optional[int] = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) A : Optional[int] = field(default=1_024 , metadata={'''help''': '''Sequence lengths used for training.'''} ) A : Optional[int] = field(default=1 , metadata={'''help''': '''Training seed.'''} ) A : Optional[int] = field( default=1_024 , metadata={'''help''': '''Interval to save checkpoints. Measured as number of forward passes not training steps.'''} , ) A : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''States path if the training should continue from a checkpoint folder.'''} ) A : Optional[bool] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''If True the data is pretokenized.'''} ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot-clean-valid''' , metadata={'''help''': '''Name or path of validation dataset.'''} ) A : Optional[int] = field(default=2 , metadata={'''help''': '''Batch size used for evaluation.'''} ) A : Optional[int] = field( default=-1 , metadata={'''help''': '''Maximum number of evaluation steps. If -1 the full dataset is evaluated.'''} ) A : Optional[int] = field(default=1_024 , metadata={'''help''': '''Length of sequences to be evaluated.'''} ) A : Optional[int] = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Model name or path of model to be evaluated.'''} ) A : Optional[int] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) A : Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''The number of human-eval tasks to run. If not included all tasks are evaluated.'''} , ) A : Optional[bool] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Sample from the language model\'s output distribution.'''} ) A : Optional[float] = field(default=0.2 , metadata={'''help''': '''Sampling temperature used for generation.'''} ) A : Optional[int] = field(default=256 , metadata={'''help''': '''Maximum number of newly generated tokens.'''} ) A : Optional[int] = field(default=0 , metadata={'''help''': '''Top-k parameter used for generation.'''} ) A : Optional[float] = field(default=0.95 , metadata={'''help''': '''Top-p parameter used for nucleus sampling.'''} ) A : Optional[int] = field(default=10 , metadata={'''help''': '''Number of generations to run in parallel.'''} ) A : Optional[int] = field( default=200 , metadata={'''help''': '''Number of completions to generate for each sample.'''} ) A : Optional[int] = field(default=1 , metadata={'''help''': '''Random seed used for evaluation.'''} ) A : Optional[str] = field( default='''eval_results.json''' , metadata={'''help''': '''Random seed used for evaluation.'''} ) A : Optional[str] = field( default='''0''' , metadata={'''help''': '''Allow `code_eval` to execute Python code on machine'''} ) A : Optional[int] = field( default=-1 , metadata={ '''help''': ( '''Determine which device to run the `text-generation` Pipeline on. -1 is CPU and any zero or positive''' ''' number corresponds to which GPU device id to run on.''' ) } , ) @dataclass class _a : '''simple docstring''' A : Optional[int] = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': '''The number of CPU cores to use for parallel preprocessing. Default uses the maximum available.''' } , ) A : Optional[str] = field( default='''transformersbook/codeparrot''' , metadata={'''help''': '''Folder or name of dataset to process.'''} ) A : Optional[str] = field( default='''codeparrot-clean''' , metadata={'''help''': '''Folder to save processed processed dataset.'''} ) A : Optional[int] = field( default=100_000 , metadata={'''help''': '''Number of files to save per JSON output file.'''} ) A : Optional[str] = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) A : Optional[float] = field( default=1_000 , metadata={'''help''': '''Maximum line length in file, otherwise file is filtered.'''} ) A : Optional[float] = field( default=100 , metadata={'''help''': '''Maximum mean line length in file, otherwise file is filtered.'''} ) A : Optional[float] = field( default=0.25 , metadata={'''help''': '''Maximum fraction of non-alphanumeric characters, otherwise file is filtered.'''} ) A : Optional[float] = field( default=1.5 , metadata={'''help''': '''Minimum character token ratio for the file, otherwise file is filtered.'''} ) A : Optional[float] = field( default=0.7 , metadata={'''help''': '''Probability for filtering config, test and uncommon files.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} , ) A : Optional[bool] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''If True, near-duplicate samples are removed.'''} ) A : Optional[float] = field( default=0.85 , metadata={'''help''': '''Jaccard threshold for near-duplicate samples.'''} ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''gpt2''' , metadata={'''help''': '''Base tokenizer to build new tokenizer from.'''} ) A : Optional[str] = field( default='''transformersbook/codeparrot-train''' , metadata={'''help''': '''Dataset to train tokenizer on.'''} ) A : Optional[str] = field(default='''content''' , metadata={'''help''': '''Column containing text data to process.'''} ) A : Optional[int] = field(default=200_000 , metadata={'''help''': '''Number of examples to train tokenizer on.'''} ) A : Optional[int] = field( default=32_768 , metadata={'''help''': '''Number of examples to train the tokenizer on.'''} ) A : Optional[str] = field(default='''codeparrot''' , metadata={'''help''': '''Name of new tokenizer.'''} ) A : Optional[bool] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Push saved tokenizer to the hub.'''} ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Name or path to the tokenizer.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot-clean-train''' , metadata={'''help''': '''Name or path to the dataset to pretokenize.'''} ) A : Optional[str] = field( default='''tokenized-codeparrot-train''' , metadata={'''help''': '''Repo name of the pretokenized data.'''} ) A : Optional[int] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Number of workers used for code evaluation.'''} ) @dataclass class _a : '''simple docstring''' A : Optional[str] = field( default='''gpt2-large''' , metadata={'''help''': '''Configuration to use for model initialization.'''} ) A : Optional[str] = field( default='''codeparrot/codeparrot''' , metadata={'''help''': '''Tokenizer attached to model.'''} ) A : Optional[str] = field(default='''codeparrot''' , metadata={'''help''': '''Name of the created model.'''} ) A : Optional[bool] = field(default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Push saved tokenizer to the hub.'''} )
28
import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case , __snake_case : List[Any] = image.size __snake_case , __snake_case : Tuple = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 __snake_case : str = image.resize((w, h) , resample=PIL_INTERPOLATION["lanczos"] ) __snake_case : int = np.array(__lowerCamelCase ).astype(np.floataa ) / 2_5_5.0 __snake_case : Union[str, Any] = image[None].transpose(0 , 3 , 1 , 2 ) __snake_case : Union[str, Any] = torch.from_numpy(__lowerCamelCase ) return 2.0 * image - 1.0 class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Tuple , lowerCamelCase : VQModel , lowerCamelCase : UNetaDModel , lowerCamelCase : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> Union[str, Any]: super().__init__() self.register_modules(vqvae=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase ) @torch.no_grad() def __call__( self : List[str] , lowerCamelCase : Union[torch.Tensor, PIL.Image.Image] = None , lowerCamelCase : Optional[int] = 1 , lowerCamelCase : Optional[int] = 100 , lowerCamelCase : Optional[float] = 0.0 , lowerCamelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , lowerCamelCase : Optional[str] = "pil" , lowerCamelCase : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : Any = 1 elif isinstance(lowerCamelCase , torch.Tensor ): __snake_case : Any = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(lowerCamelCase )}' ) if isinstance(lowerCamelCase , PIL.Image.Image ): __snake_case : List[Any] = preprocess(lowerCamelCase ) __snake_case , __snake_case : int = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image __snake_case : str = (batch_size, self.unet.config.in_channels // 2, height, width) __snake_case : str = next(self.unet.parameters() ).dtype __snake_case : Tuple = randn_tensor(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __snake_case : List[Any] = image.to(device=self.device , dtype=lowerCamelCase ) # set timesteps and move to the correct device self.scheduler.set_timesteps(lowerCamelCase , device=self.device ) __snake_case : str = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler __snake_case : Dict = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] __snake_case : Union[str, Any] = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __snake_case : int = {} if accepts_eta: __snake_case : List[str] = eta for t in self.progress_bar(lowerCamelCase ): # concat latents and low resolution image in the channel dimension. __snake_case : Union[str, Any] = torch.cat([latents, image] , dim=1 ) __snake_case : Optional[Any] = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __snake_case : int = self.unet(lowerCamelCase , lowerCamelCase ).sample # compute the previous noisy sample x_t -> x_t-1 __snake_case : Union[str, Any] = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # decode the image latents with the VQVAE __snake_case : List[Any] = self.vqvae.decode(lowerCamelCase ).sample __snake_case : Dict = torch.clamp(lowerCamelCase , -1.0 , 1.0 ) __snake_case : Any = image / 2 + 0.5 __snake_case : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __snake_case : Tuple = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase )
81
0
"""simple docstring""" # flake8: noqa # Lint as: python3 from typing import Dict, List, Optional, Type from .. import config from ..utils import logging from .formatting import ( ArrowFormatter, CustomFormatter, Formatter, PandasFormatter, PythonFormatter, TensorFormatter, format_table, query_table, ) from .np_formatter import NumpyFormatter A_ = logging.get_logger(__name__) A_ = {} A_ = {} A_ = {} def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = None ,): lowerCamelCase_ = aliases if aliases is not None else [] if format_type in _FORMAT_TYPES: logger.warning( f"Overwriting format type '{format_type}' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})" ) lowerCamelCase_ = formatter_cls for alias in set(aliases + [format_type] ): if alias in _FORMAT_TYPES_ALIASES: logger.warning( f"Overwriting format type alias '{alias}' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})" ) lowerCamelCase_ = format_type def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__ = None ): lowerCamelCase_ = aliases if aliases is not None else [] for alias in set(aliases + [format_type] ): lowerCamelCase_ = unavailable_error # Here we define all the available formatting functions that can be used by `Dataset.set_format` _register_formatter(PythonFormatter, None, aliases=["""python"""]) _register_formatter(ArrowFormatter, """arrow""", aliases=["""pa""", """pyarrow"""]) _register_formatter(NumpyFormatter, """numpy""", aliases=["""np"""]) _register_formatter(PandasFormatter, """pandas""", aliases=["""pd"""]) _register_formatter(CustomFormatter, """custom""") if config.TORCH_AVAILABLE: from .torch_formatter import TorchFormatter _register_formatter(TorchFormatter, """torch""", aliases=["""pt""", """pytorch"""]) else: A_ = ValueError("""PyTorch needs to be installed to be able to return PyTorch tensors.""") _register_unavailable_formatter(_torch_error, """torch""", aliases=["""pt""", """pytorch"""]) if config.TF_AVAILABLE: from .tf_formatter import TFFormatter _register_formatter(TFFormatter, """tensorflow""", aliases=["""tf"""]) else: A_ = ValueError("""Tensorflow needs to be installed to be able to return Tensorflow tensors.""") _register_unavailable_formatter(_tf_error, """tensorflow""", aliases=["""tf"""]) if config.JAX_AVAILABLE: from .jax_formatter import JaxFormatter _register_formatter(JaxFormatter, """jax""", aliases=[]) else: A_ = ValueError("""JAX needs to be installed to be able to return JAX arrays.""") _register_unavailable_formatter(_jax_error, """jax""", aliases=[]) def lowercase ( lowerCAmelCase__ ): if format_type in _FORMAT_TYPES_ALIASES: return _FORMAT_TYPES_ALIASES[format_type] else: return format_type def lowercase ( lowerCAmelCase__ ,**lowerCAmelCase__ ): lowerCamelCase_ = get_format_type_from_alias(lowerCAmelCase__ ) if format_type in _FORMAT_TYPES: return _FORMAT_TYPES[format_type](**lowerCAmelCase__ ) if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE: raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type] else: raise ValueError( f"Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None )}, but got '{format_type}'" )
29
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 a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : str = AutoencoderKL __UpperCAmelCase : Optional[Any] = "sample" __UpperCAmelCase : Optional[int] = 1e-2 @property def __snake_case ( self : Dict ) -> Optional[Any]: __snake_case : Optional[Any] = 4 __snake_case : Tuple = 3 __snake_case : List[str] = (32, 32) __snake_case : str = floats_tensor((batch_size, num_channels) + sizes ).to(lowerCamelCase ) return {"sample": image} @property def __snake_case ( self : Union[str, Any] ) -> Tuple: return (3, 32, 32) @property def __snake_case ( self : int ) -> int: return (3, 32, 32) def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Optional[Any] = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } __snake_case : Any = self.dummy_input return init_dict, inputs_dict def __snake_case ( self : str ) -> Dict: pass def __snake_case ( self : Tuple ) -> List[str]: pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def __snake_case ( self : Any ) -> Optional[Any]: # enable deterministic behavior for gradient checkpointing __snake_case , __snake_case : int = self.prepare_init_args_and_inputs_for_common() __snake_case : str = self.model_class(**lowerCamelCase ) model.to(lowerCamelCase ) assert not model.is_gradient_checkpointing and model.training __snake_case : str = model(**lowerCamelCase ).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() __snake_case : Any = torch.randn_like(lowerCamelCase ) __snake_case : str = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing __snake_case : Optional[int] = self.model_class(**lowerCamelCase ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(lowerCamelCase ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training __snake_case : int = model_a(**lowerCamelCase ).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() __snake_case : Union[str, Any] = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) __snake_case : Optional[int] = dict(model.named_parameters() ) __snake_case : List[Any] = 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 __snake_case ( self : List[Any] ) -> Optional[int]: __snake_case , __snake_case : Optional[Any] = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(lowerCamelCase ) __snake_case : Optional[Any] = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def __snake_case ( self : Optional[Any] ) -> Union[str, Any]: __snake_case : Tuple = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) __snake_case : Dict = model.to(lowerCamelCase ) model.eval() if torch_device == "mps": __snake_case : int = torch.manual_seed(0 ) else: __snake_case : str = torch.Generator(device=lowerCamelCase ).manual_seed(0 ) __snake_case : List[str] = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) __snake_case : Union[str, Any] = image.to(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , sample_posterior=lowerCamelCase , generator=lowerCamelCase ).sample __snake_case : List[Any] = 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": __snake_case : Union[str, Any] = 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": __snake_case : Tuple = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: __snake_case : List[str] = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(lowerCamelCase , lowerCamelCase , rtol=1E-2 ) ) @slow class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : int , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] ) -> List[str]: return F'gaussian_noise_s={seed}_shape={"_".join([str(lowerCamelCase ) for s in shape] )}.npy' def __snake_case ( self : List[Any] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Tuple , lowerCamelCase : List[Any]=0 , lowerCamelCase : Tuple=(4, 3, 512, 512) , lowerCamelCase : Optional[int]=False ) -> str: __snake_case : List[Any] = torch.floataa if fpaa else torch.floataa __snake_case : Tuple = torch.from_numpy(load_hf_numpy(self.get_file_format(lowerCamelCase , lowerCamelCase ) ) ).to(lowerCamelCase ).to(lowerCamelCase ) return image def __snake_case ( self : Optional[Any] , lowerCamelCase : int="CompVis/stable-diffusion-v1-4" , lowerCamelCase : int=False ) -> int: __snake_case : str = "fp16" if fpaa else None __snake_case : int = torch.floataa if fpaa else torch.floataa __snake_case : int = AutoencoderKL.from_pretrained( lowerCamelCase , subfolder="vae" , torch_dtype=lowerCamelCase , revision=lowerCamelCase , ) model.to(lowerCamelCase ).eval() return model def __snake_case ( self : str , lowerCamelCase : int=0 ) -> Optional[Any]: if torch_device == "mps": return torch.manual_seed(lowerCamelCase ) return torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[str] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] , lowerCamelCase : Optional[Any] ) -> List[Any]: __snake_case : Optional[Any] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) __snake_case : Tuple = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : List[Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : int = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : Any , lowerCamelCase : List[str] , lowerCamelCase : List[str] ) -> Tuple: __snake_case : Any = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , fpaa=lowerCamelCase ) __snake_case : List[Any] = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : str = model(lowerCamelCase , generator=lowerCamelCase , sample_posterior=lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Any = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Any , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase ) with torch.no_grad(): __snake_case : int = model(lowerCamelCase ).sample assert sample.shape == image.shape __snake_case : Union[str, Any] = sample[-1, -2:, -2:, :2].flatten().float().cpu() __snake_case : List[str] = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : List[str] , lowerCamelCase : Tuple , lowerCamelCase : Any ) -> Optional[Any]: __snake_case : List[str] = self.get_sd_vae_model() __snake_case : List[Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : str = sample[-1, -2:, :2, -2:].flatten().cpu() __snake_case : Optional[int] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def __snake_case ( self : str , lowerCamelCase : Optional[int] , lowerCamelCase : Dict ) -> int: __snake_case : int = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : List[str] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : Union[str, Any] = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] __snake_case : Optional[Any] = sample[-1, -2:, :2, -2:].flatten().float().cpu() __snake_case : Optional[Any] = torch.tensor(lowerCamelCase ) assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=5E-3 ) @parameterized.expand([(13,), (16,), (27,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : Tuple , lowerCamelCase : List[Any] ) -> Tuple: __snake_case : Dict = self.get_sd_vae_model(fpaa=lowerCamelCase ) __snake_case : Any = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) , fpaa=lowerCamelCase ) with torch.no_grad(): __snake_case : str = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Any = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-1 ) @parameterized.expand([(13,), (16,), (37,)] ) @require_torch_gpu @unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." ) def __snake_case ( self : List[Any] , lowerCamelCase : Any ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : Union[str, Any] = self.get_sd_image(lowerCamelCase , shape=(3, 4, 64, 64) ) with torch.no_grad(): __snake_case : List[Any] = model.decode(lowerCamelCase ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): __snake_case : Dict = model.decode(lowerCamelCase ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def __snake_case ( self : List[Any] , lowerCamelCase : List[Any] , lowerCamelCase : Dict ) -> Optional[int]: __snake_case : str = self.get_sd_vae_model() __snake_case : int = self.get_sd_image(lowerCamelCase ) __snake_case : int = self.get_generator(lowerCamelCase ) with torch.no_grad(): __snake_case : Optional[Any] = model.encode(lowerCamelCase ).latent_dist __snake_case : Dict = dist.sample(generator=lowerCamelCase ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] __snake_case : List[str] = sample[0, -1, -3:, -3:].flatten().cpu() __snake_case : Dict = torch.tensor(lowerCamelCase ) __snake_case : Dict = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(lowerCamelCase , lowerCamelCase , atol=lowerCamelCase )
81
0
from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : int = int(number**0.5 ) return number == sq * sq def lowerCamelCase__ ( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ): '''simple docstring''' UpperCAmelCase_ : int = x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den UpperCAmelCase_ : int = x_den * y_den * z_den UpperCAmelCase_ : int = gcd(_lowercase , _lowercase ) top //= hcf bottom //= hcf return top, bottom def lowerCamelCase__ ( _lowercase = 35 ): '''simple docstring''' UpperCAmelCase_ : set = set() UpperCAmelCase_ : int UpperCAmelCase_ : Fraction = Fraction(0 ) UpperCAmelCase_ : tuple[int, int] for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 UpperCAmelCase_ : Union[str, Any] = x_num * y_den + x_den * y_num UpperCAmelCase_ : List[Any] = x_den * y_den UpperCAmelCase_ : str = gcd(_lowercase , _lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCAmelCase_ : List[Any] = add_three( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) unique_s.add(_lowercase ) # n=2 UpperCAmelCase_ : List[Any] = ( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) UpperCAmelCase_ : Union[str, Any] = x_den * x_den * y_den * y_den if is_sq(_lowercase ) and is_sq(_lowercase ): UpperCAmelCase_ : Optional[int] = int(sqrt(_lowercase ) ) UpperCAmelCase_ : Tuple = int(sqrt(_lowercase ) ) UpperCAmelCase_ : Dict = gcd(_lowercase , _lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCAmelCase_ : Optional[int] = add_three( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) unique_s.add(_lowercase ) # n=-1 UpperCAmelCase_ : List[Any] = x_num * y_num UpperCAmelCase_ : Optional[int] = x_den * y_num + x_num * y_den UpperCAmelCase_ : Dict = gcd(_lowercase , _lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCAmelCase_ : List[Any] = add_three( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) unique_s.add(_lowercase ) # n=2 UpperCAmelCase_ : Tuple = x_num * x_num * y_num * y_num UpperCAmelCase_ : Dict = ( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(_lowercase ) and is_sq(_lowercase ): UpperCAmelCase_ : int = int(sqrt(_lowercase ) ) UpperCAmelCase_ : Any = int(sqrt(_lowercase ) ) UpperCAmelCase_ : Optional[int] = gcd(_lowercase , _lowercase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: UpperCAmelCase_ : List[Any] = add_three( _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) unique_s.add(_lowercase ) for num, den in unique_s: total += Fraction(_lowercase , _lowercase ) return total.denominator + total.numerator if __name__ == "__main__": print(F"""{solution() = }""")
30
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _snake_case : Optional[int] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : Optional[Any] , *lowerCamelCase : Any , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
0
from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowerCamelCase__ : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCamelCase__ : Dict = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] , __UpperCAmelCase : int , __UpperCAmelCase : Any=8 ) -> Dict: SCREAMING_SNAKE_CASE_ = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 SCREAMING_SNAKE_CASE_ = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCamelCase_ ( _SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Dict , _lowerCAmelCase : UNetaDConditionModel , _lowerCAmelCase : DDPMScheduler , _lowerCAmelCase : VQModel , ): super().__init__() self.register_modules( unet=_lowerCAmelCase , scheduler=_lowerCAmelCase , movq=_lowerCAmelCase , ) SCREAMING_SNAKE_CASE_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowerCAmelCase_ ( self : Union[str, Any] , _lowerCAmelCase : str , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[str] , _lowerCAmelCase : List[Any] ): if latents is None: SCREAMING_SNAKE_CASE_ = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}" ) SCREAMING_SNAKE_CASE_ = latents.to(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase_ ( self : Optional[Any] , _lowerCAmelCase : str=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) SCREAMING_SNAKE_CASE_ = torch.device(F"cuda:{gpu_id}" ) SCREAMING_SNAKE_CASE_ = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCAmelCase , _lowerCAmelCase ) def lowerCAmelCase_ ( self : List[str] , _lowerCAmelCase : Any=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) SCREAMING_SNAKE_CASE_ = torch.device(F"cuda:{gpu_id}" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=_lowerCAmelCase ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) SCREAMING_SNAKE_CASE_ = None for cpu_offloaded_model in [self.unet, self.movq]: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = cpu_offload_with_hook(_lowerCAmelCase , _lowerCAmelCase , prev_module_hook=_lowerCAmelCase ) # We'll offload the last model manually. SCREAMING_SNAKE_CASE_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowerCAmelCase_ ( self : int ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(_lowerCAmelCase , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(_lowerCAmelCase ) def __call__( self : Any , _lowerCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , _lowerCAmelCase : Union[torch.FloatTensor, List[torch.FloatTensor]] , _lowerCAmelCase : int = 512 , _lowerCAmelCase : int = 512 , _lowerCAmelCase : int = 100 , _lowerCAmelCase : float = 4.0 , _lowerCAmelCase : int = 1 , _lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCAmelCase : Optional[torch.FloatTensor] = None , _lowerCAmelCase : Optional[str] = "pil" , _lowerCAmelCase : bool = True , ): SCREAMING_SNAKE_CASE_ = self._execution_device SCREAMING_SNAKE_CASE_ = guidance_scale > 1.0 if isinstance(_lowerCAmelCase , _lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = torch.cat(_lowerCAmelCase , dim=0 ) SCREAMING_SNAKE_CASE_ = image_embeds.shape[0] * num_images_per_prompt if isinstance(_lowerCAmelCase , _lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = torch.cat(_lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ = image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) SCREAMING_SNAKE_CASE_ = negative_image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) SCREAMING_SNAKE_CASE_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_lowerCAmelCase ) self.scheduler.set_timesteps(_lowerCAmelCase , device=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = self.scheduler.timesteps SCREAMING_SNAKE_CASE_ = self.unet.config.in_channels SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = downscale_height_and_width(_lowerCAmelCase , _lowerCAmelCase , self.movq_scale_factor ) # create initial latent SCREAMING_SNAKE_CASE_ = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , self.scheduler , ) for i, t in enumerate(self.progress_bar(_lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE_ = {'image_embeds': image_embeds} SCREAMING_SNAKE_CASE_ = self.unet( sample=_lowerCAmelCase , timestep=_lowerCAmelCase , encoder_hidden_states=_lowerCAmelCase , added_cond_kwargs=_lowerCAmelCase , return_dict=_lowerCAmelCase , )[0] if do_classifier_free_guidance: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred.split(latents.shape[1] , dim=1 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = variance_pred.chunk(2 ) SCREAMING_SNAKE_CASE_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) SCREAMING_SNAKE_CASE_ = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE_ = self.scheduler.step( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase , )[0] # post-processing SCREAMING_SNAKE_CASE_ = self.movq.decode(_lowerCAmelCase , force_not_quantize=_lowerCAmelCase )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}" ) if output_type in ["np", "pil"]: SCREAMING_SNAKE_CASE_ = image * 0.5 + 0.5 SCREAMING_SNAKE_CASE_ = image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": SCREAMING_SNAKE_CASE_ = self.numpy_to_pil(_lowerCAmelCase ) if not return_dict: return (image,) return ImagePipelineOutput(images=_lowerCAmelCase )
31
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Tuple ) -> Optional[Any]: __snake_case : Dict = tempfile.mkdtemp() __snake_case : Any = SamImageProcessor() __snake_case : Optional[int] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : Optional[Any] , **lowerCamelCase : Optional[int] ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[Any] ) -> Dict: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : int ) -> List[Any]: __snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : int = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : List[Any] ) -> Dict: __snake_case : int = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Dict = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Optional[Any] = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : List[str] ) -> Tuple: __snake_case : int = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Optional[int] = self.prepare_image_inputs() __snake_case : List[str] = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : Dict = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_torch def __snake_case ( self : Optional[Any] ) -> Dict: __snake_case : Tuple = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[str] = [torch.ones((1, 3, 5, 5) )] __snake_case : Tuple = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : int = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , torch.tensor(lowerCamelCase ) , torch.tensor(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : List[str] = [np.ones((1, 3, 5, 5) )] __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : str = [[1, 0], [0, 1]] with self.assertRaises(lowerCamelCase ): __snake_case : Optional[int] = processor.post_process_masks(lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) ) @require_vision @require_tf class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[Any] ) -> Union[str, Any]: __snake_case : int = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : str , **lowerCamelCase : Any ) -> Tuple: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> Any: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : str ) -> List[Any]: __snake_case : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : Dict = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def __snake_case ( self : int ) -> List[str]: __snake_case : List[Any] = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __snake_case : Optional[Any] = self.get_image_processor(do_normalize=lowerCamelCase , padding_value=1.0 ) __snake_case : Tuple = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCamelCase ) def __snake_case ( self : Union[str, Any] ) -> List[Any]: __snake_case : str = self.get_image_processor() __snake_case : Union[str, Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : int = image_processor(lowerCamelCase , return_tensors="np" ) __snake_case : List[str] = processor(images=lowerCamelCase , return_tensors="np" ) input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) @require_tf def __snake_case ( self : Any ) -> Optional[int]: __snake_case : List[str] = self.get_image_processor() __snake_case : Dict = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Union[str, Any] = [tf.ones((1, 3, 5, 5) )] __snake_case : List[Any] = [[1764, 2646]] __snake_case : Dict = [[683, 1024]] __snake_case : List[str] = processor.post_process_masks(lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Optional[Any] = processor.post_process_masks( lowerCamelCase , tf.convert_to_tensor(lowerCamelCase ) , tf.convert_to_tensor(lowerCamelCase ) , return_tensors="tf" , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np __snake_case : Union[str, Any] = [np.ones((1, 3, 5, 5) )] __snake_case : List[str] = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) __snake_case : Tuple = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): __snake_case : Dict = processor.post_process_masks( lowerCamelCase , np.array(lowerCamelCase ) , np.array(lowerCamelCase ) , return_tensors="tf" ) @require_vision @require_torchvision class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : List[str] ) -> str: __snake_case : Optional[int] = tempfile.mkdtemp() __snake_case : str = SamImageProcessor() __snake_case : List[Any] = SamProcessor(lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) def __snake_case ( self : List[str] , **lowerCamelCase : Any ) -> Dict: return AutoProcessor.from_pretrained(self.tmpdirname , **lowerCamelCase ).image_processor def __snake_case ( self : Optional[int] ) -> List[Any]: shutil.rmtree(self.tmpdirname ) def __snake_case ( self : Optional[int] ) -> Optional[int]: __snake_case : str = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] __snake_case : List[Any] = [Image.fromarray(np.moveaxis(lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def __snake_case ( self : Union[str, Any] ) -> List[str]: __snake_case : str = self.get_image_processor() __snake_case : str = SamProcessor(image_processor=lowerCamelCase ) __snake_case : List[Any] = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) __snake_case : Dict = [tf.convert_to_tensor(lowerCamelCase )] __snake_case : List[Any] = [torch.tensor(lowerCamelCase )] __snake_case : Optional[Any] = [[1764, 2646]] __snake_case : Optional[int] = [[683, 1024]] __snake_case : Union[str, Any] = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="tf" ) __snake_case : Dict = processor.post_process_masks( lowerCamelCase , lowerCamelCase , lowerCamelCase , return_tensors="pt" ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def __snake_case ( self : List[Any] ) -> List[str]: __snake_case : Any = self.get_image_processor() __snake_case : List[Any] = SamProcessor(image_processor=lowerCamelCase ) __snake_case : Dict = self.prepare_image_inputs() __snake_case : Any = image_processor(lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Optional[Any] = processor(images=lowerCamelCase , return_tensors="pt" )["pixel_values"].numpy() __snake_case : Tuple = image_processor(lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() __snake_case : List[Any] = processor(images=lowerCamelCase , return_tensors="tf" )["pixel_values"].numpy() self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) ) self.assertTrue(np.allclose(lowerCamelCase , lowerCamelCase ) )
81
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def A__ ( SCREAMING_SNAKE_CASE_ : dict ) -> tuple: """simple docstring""" return (data["data"], data["target"]) def A__ ( SCREAMING_SNAKE_CASE_ : np.ndarray , SCREAMING_SNAKE_CASE_ : np.ndarray ) -> XGBClassifier: """simple docstring""" _UpperCAmelCase = XGBClassifier() classifier.fit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return classifier def A__ ( ) -> None: """simple docstring""" _UpperCAmelCase = load_iris() _UpperCAmelCase , _UpperCAmelCase = data_handling(SCREAMING_SNAKE_CASE_ ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = train_test_split( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , test_size=0.2_5 ) _UpperCAmelCase = iris['''target_names'''] # Create an XGBoost Classifier from the training data _UpperCAmelCase = xgboost(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , display_labels=SCREAMING_SNAKE_CASE_ , cmap='''Blues''' , normalize='''true''' , ) plt.title('''Normalized Confusion Matrix - IRIS Dataset''' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
32
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _snake_case : List[str] = logging.get_logger(__name__) class a (_lowerCAmelCase ): """simple docstring""" def __init__( self : List[str] , *lowerCamelCase : str , **lowerCamelCase : Union[str, Any] ) -> None: warnings.warn( "The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use DeiTImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
81
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class __magic_name__ (unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE__ ( self:str ): snake_case__ = '''ZinengTang/tvlt-base''' snake_case__ = tempfile.mkdtemp() def SCREAMING_SNAKE_CASE__ ( self:Dict , **_a:List[Any] ): return TvltImageProcessor.from_pretrained(self.checkpoint , **_a ) def SCREAMING_SNAKE_CASE__ ( self:Optional[Any] , **_a:Tuple ): return TvltFeatureExtractor.from_pretrained(self.checkpoint , **_a ) def SCREAMING_SNAKE_CASE__ ( self:Dict ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE__ ( self:List[str] ): snake_case__ = self.get_image_processor() snake_case__ = self.get_feature_extractor() snake_case__ = TvltProcessor(image_processor=_a , feature_extractor=_a ) processor.save_pretrained(self.tmpdirname ) snake_case__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , _a ) self.assertIsInstance(processor.image_processor , _a ) def SCREAMING_SNAKE_CASE__ ( self:Dict ): snake_case__ = self.get_image_processor() snake_case__ = self.get_feature_extractor() snake_case__ = TvltProcessor(image_processor=_a , feature_extractor=_a ) snake_case__ = np.ones([1_20_00] ) snake_case__ = feature_extractor(_a , return_tensors='''np''' ) snake_case__ = processor(audio=_a , return_tensors='''np''' ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE__ ( self:List[Any] ): snake_case__ = self.get_image_processor() snake_case__ = self.get_feature_extractor() snake_case__ = TvltProcessor(image_processor=_a , feature_extractor=_a ) snake_case__ = np.ones([3, 2_24, 2_24] ) snake_case__ = image_processor(_a , return_tensors='''np''' ) snake_case__ = processor(images=_a , return_tensors='''np''' ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE__ ( self:Any ): snake_case__ = self.get_image_processor() snake_case__ = self.get_feature_extractor() snake_case__ = TvltProcessor(image_processor=_a , feature_extractor=_a ) snake_case__ = np.ones([1_20_00] ) snake_case__ = np.ones([3, 2_24, 2_24] ) snake_case__ = processor(audio=_a , images=_a ) self.assertListEqual(list(inputs.keys() ) , ['''audio_values''', '''audio_mask''', '''pixel_values''', '''pixel_mask'''] ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def SCREAMING_SNAKE_CASE__ ( self:List[Any] ): snake_case__ = self.get_image_processor() snake_case__ = self.get_feature_extractor() snake_case__ = TvltProcessor(image_processor=_a , feature_extractor=_a ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg='''`processor` and `image_processor`+`feature_extractor` model input names do not match''' , )
33
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _snake_case : Union[str, Any] = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : List[Any] = ["OwlViTFeatureExtractor"] _snake_case : Optional[int] = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case : int = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _snake_case : Optional[int] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
81
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase_ ) class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = field(default='''automatic-speech-recognition''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) A_ = Features({'''audio''': Audio()} ) A_ = Features({'''transcription''': Value('''string''' )} ) A_ = "audio" A_ = "transcription" def UpperCAmelCase__ ( self , lowerCamelCase_) -> str: if self.audio_column not in features: raise ValueError(F'Column {self.audio_column} is not present in features.') if not isinstance(features[self.audio_column] , lowerCamelCase_): raise ValueError(F'Column {self.audio_column} is not an Audio type.') UpperCamelCase = copy.deepcopy(self) UpperCamelCase = self.input_schema.copy() UpperCamelCase = features[self.audio_column] UpperCamelCase = input_schema return task_template @property def UpperCAmelCase__ ( self) -> Dict[str, str]: return {self.audio_column: "audio", self.transcription_column: "transcription"}
34
from ....configuration_utils import PretrainedConfig from ....utils import logging _snake_case : int = logging.get_logger(__name__) _snake_case : str = { "Visual-Attention-Network/van-base": ( "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json" ), } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : List[Any] = "van" def __init__( self : Optional[int] , lowerCamelCase : Any=224 , lowerCamelCase : str=3 , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : Dict=[4, 2, 2, 2] , lowerCamelCase : List[Any]=[64, 128, 320, 512] , lowerCamelCase : str=[3, 3, 12, 3] , lowerCamelCase : Dict=[8, 8, 4, 4] , lowerCamelCase : Any="gelu" , lowerCamelCase : Optional[int]=0.02 , lowerCamelCase : Tuple=1E-6 , lowerCamelCase : Optional[int]=1E-2 , lowerCamelCase : int=0.0 , lowerCamelCase : Optional[Any]=0.0 , **lowerCamelCase : Optional[int] , ) -> int: super().__init__(**lowerCamelCase ) __snake_case : Union[str, Any] = image_size __snake_case : Any = num_channels __snake_case : Any = patch_sizes __snake_case : List[Any] = strides __snake_case : str = hidden_sizes __snake_case : Dict = depths __snake_case : Optional[int] = mlp_ratios __snake_case : Dict = hidden_act __snake_case : Union[str, Any] = initializer_range __snake_case : List[str] = layer_norm_eps __snake_case : Optional[int] = layer_scale_init_value __snake_case : List[Any] = drop_path_rate __snake_case : int = dropout_rate
81
0
import requests from bsa import BeautifulSoup def a ( A__ = "https://www.worldometers.info/coronavirus" ) -> dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = BeautifulSoup(requests.get(A__ ).text , '''html.parser''' ) SCREAMING_SNAKE_CASE__ : List[str] = soup.findAll('''h1''' ) SCREAMING_SNAKE_CASE__ : int = soup.findAll('''div''' , {'''class''': '''maincounter-number'''} ) keys += soup.findAll('''span''' , {'''class''': '''panel-title'''} ) values += soup.findAll('''div''' , {'''class''': '''number-table-main'''} ) return {key.text.strip(): value.text.strip() for key, value in zip(A__ , A__ )} if __name__ == "__main__": print('\033[1m' + 'COVID-19 Status of the World' + '\033[0m\n') for key, value in world_covidaa_stats().items(): print(F'''{key}\n{value}\n''')
35
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer _snake_case : Union[str, Any] = logging.getLogger(__name__) def lowerCAmelCase_ ( ): __snake_case : int = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1_0_0_0 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=5_1_2 , help="Maximum sequence length. For training on TPUs, it helps to have a maximum" " sequence length that is a multiple of 8." , ) parser.add_argument( "--output_dir" , default="tf-tpu" , type=__lowerCamelCase , help="Output directory where the TFRecord shards will be saved. If the" " path is appended with `gs://` ('gs://tf-tpu', for example) then the TFRecord" " shards will be directly saved to a Google Cloud Storage bucket." , ) __snake_case : List[str] = parser.parse_args() return args def lowerCAmelCase_ ( __lowerCamelCase ): def fn(__lowerCamelCase ): return tokenizer(examples["text"] ) return fn def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = [] for i in range(len(tokenized_data["input_ids"] ) ): __snake_case : Tuple = { "input_ids": tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data["input_ids"][i] ) ), "attention_mask": tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data["attention_mask"][i] ) ), } __snake_case : List[Any] = tf.train.Features(feature=__lowerCamelCase ) __snake_case : str = tf.train.Example(features=__lowerCamelCase ) __snake_case : List[str] = example.SerializeToString() records.append(__lowerCamelCase ) return records def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Optional[int] = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: __snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) __snake_case : Dict = dataset.select(range(__lowerCamelCase ) ) print(F'Limiting the dataset to {args.limit} entries.' ) __snake_case : Dict = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) __snake_case : Dict = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: __snake_case : str = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. __snake_case : Any = tokenize_function(__lowerCamelCase ) __snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , num_proc=4 , remove_columns=["text"] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__lowerCamelCase ): # Concatenate all texts. __snake_case : List[str] = {k: sum(examples[k] , [] ) for k in examples.keys()} __snake_case : List[Any] = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 __snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. __snake_case : int = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result __snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1_0_0_0 , num_proc=4 ) __snake_case : Optional[Any] = 0 __snake_case : Optional[Any] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): __snake_case : List[str] = grouped_dataset[shard : shard + args.shard_size] __snake_case : Any = len(dataset_snapshot["input_ids"] ) __snake_case : List[Any] = os.path.join(__lowerCamelCase , F'dataset-{shard_count}-{records_containing}.tfrecord' ) __snake_case : Optional[Any] = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): __snake_case : Union[str, Any] = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) shard_count += 1 total_records += records_containing with open(F'split-{args.split}-records-count.txt' , "w" ) as f: print(F'Total {args.split} records: {total_records}' , file=__lowerCamelCase ) if __name__ == "__main__": _snake_case : List[Any] = parse_args() main(args)
81
0
import requests from bsa import BeautifulSoup def lowercase ( __A : str = "AAPL" ) -> str: '''simple docstring''' snake_case : List[Any] = f"""https://in.finance.yahoo.com/quote/{symbol}?s={symbol}""" snake_case : Dict = BeautifulSoup(requests.get(__A ).text , """html.parser""" ) snake_case : Optional[int] = """My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
36
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) _snake_case : List[Any] = "\\n Text data.\n Second line of data." _snake_case : Tuple = "file" @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / (FILE_PATH + ".zstd") __snake_case : Optional[Any] = bytes(__lowerCamelCase , "utf-8" ) with zstd.open(__lowerCamelCase , "wb" ) as f: f.write(__lowerCamelCase ) return path @pytest.fixture def lowerCAmelCase_ ( __lowerCamelCase ): with open(os.path.join(tmpfs.local_root_dir , __lowerCamelCase ) , "w" ) as f: f.write(__lowerCamelCase ) return FILE_PATH @pytest.mark.parametrize("compression_format" , ["gzip", "xz", "zstd"] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Optional[int] = {"gzip": gz_file, "xz": xz_file, "zstd": zstd_path} __snake_case : str = input_paths[compression_format] __snake_case : Optional[Any] = tmp_path / "cache" __snake_case : Optional[int] = DownloadConfig(cache_dir=__lowerCamelCase , extract_compressed_file=__lowerCamelCase ) __snake_case : Union[str, Any] = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) with open(__lowerCamelCase ) as f: __snake_case : Dict = f.read() with open(__lowerCamelCase ) as f: __snake_case : Tuple = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("default_extracted" , [True, False] ) @pytest.mark.parametrize("default_cache_dir" , [True, False] ) def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : Tuple = "custom_cache" __snake_case : List[str] = "custom_extracted_dir" __snake_case : Any = tmp_path / "custom_extracted_path" if default_extracted: __snake_case : List[Any] = ("downloads" if default_cache_dir else custom_cache_dir, "extracted") else: monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_DIR" , __lowerCamelCase ) monkeypatch.setattr("datasets.config.EXTRACTED_DATASETS_PATH" , str(__lowerCamelCase ) ) __snake_case : Optional[Any] = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __snake_case : Optional[int] = xz_file __snake_case : Optional[int] = ( DownloadConfig(extract_compressed_file=__lowerCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=__lowerCamelCase ) ) __snake_case : str = cached_path(__lowerCamelCase , download_config=__lowerCamelCase ) assert Path(__lowerCamelCase ).parent.parts[-2:] == expected def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : Optional[Any] = str(Path(__lowerCamelCase ).resolve() ) assert cached_path(__lowerCamelCase ) == text_file # relative path __snake_case : Any = str(Path(__lowerCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(__lowerCamelCase ) == text_file def lowerCAmelCase_ ( __lowerCamelCase ): # absolute path __snake_case : List[Any] = str(tmp_path.resolve() / "__missing_file__.txt" ) with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) # relative path __snake_case : Optional[int] = "./__missing_file__.txt" with pytest.raises(__lowerCamelCase ): cached_path(__lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : str = get_from_cache(F'tmp://{tmpfs_file}' ) with open(__lowerCamelCase ) as f: __snake_case : Union[str, Any] = f.read() assert output_file_content == FILE_CONTENT @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( ): with pytest.raises(__lowerCamelCase ): cached_path("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): http_get("https://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): http_head("https://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[str] = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): ftp_get("ftp://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): ftp_head("ftp://huggingface.co" ) @patch("datasets.config.HF_DATASETS_OFFLINE" , __lowerCamelCase ) def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : Tuple = tmp_path_factory.mktemp("data" ) / "file.html" with pytest.raises(__lowerCamelCase ): fsspec_get("s3://huggingface.co" , temp_file=__lowerCamelCase ) with pytest.raises(__lowerCamelCase ): fsspec_head("s3://huggingface.co" )
81
0
import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase : Optional[Any] = get_tests_dir("""fixtures/spiece.model""") @require_sentencepiece @require_tokenizers class A__ ( A__ , unittest.TestCase ): """simple docstring""" _lowercase = DebertaVaTokenizer _lowercase = DebertaVaTokenizerFast _lowercase = True _lowercase = True def _UpperCamelCase( self : Tuple ): super().setUp() # We have a SentencePiece fixture for testing a__ : Optional[int] = DebertaVaTokenizer(lowerCamelCase__ , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def _UpperCamelCase( self : Dict , lowerCamelCase__ : Dict ): a__ : Optional[int] = "this is a test" a__ : Dict = "this is a test" return input_text, output_text def _UpperCamelCase( self : Optional[Any] ): a__ : int = "<pad>" a__ : List[str] = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase__ ) , lowerCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase__ ) , lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): a__ : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "[PAD]" ) self.assertEqual(len(lowerCamelCase__ ) , 30_001 ) def _UpperCamelCase( self : Optional[int] ): self.assertEqual(self.get_tokenizer().vocab_size , 30_000 ) def _UpperCamelCase( self : Optional[int] ): # fmt: off a__ : List[str] = " \tHeLLo!how \n Are yoU? " a__ : Any = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on a__ : Tuple = DebertaVaTokenizer(lowerCamelCase__ , do_lower_case=lowerCamelCase__ ) a__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Union[str, Any] = DebertaVaTokenizerFast(lowerCamelCase__ , do_lower_case=lowerCamelCase__ ) a__ : str = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def _UpperCamelCase( self : Any ): pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def _UpperCamelCase( self : Optional[int] ): pass def _UpperCamelCase( self : Optional[Any] ): # fmt: off a__ : Optional[int] = "I was born in 92000, and this is falsé." a__ : Union[str, Any] = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on a__ : Any = DebertaVaTokenizer(lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : int = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Optional[int] = DebertaVaTokenizerFast(lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Optional[int] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): # fmt: off a__ : int = "I was born in 92000, and this is falsé." a__ : Optional[Any] = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on a__ : Tuple = DebertaVaTokenizer(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Union[str, Any] = DebertaVaTokenizerFast(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : Optional[int] ): # fmt: off a__ : int = "I was born in 92000, and this is falsé." a__ : Dict = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on a__ : Dict = DebertaVaTokenizer(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Tuple = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : List[str] = DebertaVaTokenizerFast(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): # fmt: off a__ : Dict = "I was born in 92000, and this is falsé." a__ : List[str] = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on a__ : Union[str, Any] = DebertaVaTokenizer(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : str = DebertaVaTokenizerFast(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : List[Any] ): # fmt: off a__ : List[Any] = " \tHeLLo!how \n Are yoU? " a__ : List[str] = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on a__ : Tuple = DebertaVaTokenizer(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Tuple = DebertaVaTokenizerFast(lowerCamelCase__ , do_lower_case=lowerCamelCase__ , split_by_punct=lowerCamelCase__ ) a__ : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : Tuple ): a__ : Tuple = self.get_tokenizer() a__ : List[Any] = self.get_rust_tokenizer() a__ : Optional[Any] = "I was born in 92000, and this is falsé." a__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) a__ : Optional[int] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Optional[int] = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) a__ : Optional[int] = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : str = self.get_rust_tokenizer() a__ : Tuple = tokenizer.encode(lowerCamelCase__ ) a__ : Tuple = rust_tokenizer.encode(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : Union[str, Any] ): a__ : Optional[int] = "This is a test" a__ : str = [13, 1, 4_398, 25, 21, 1_289] a__ : Any = ["▁", "T", "his", "▁is", "▁a", "▁test"] a__ : int = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] a__ : List[str] = DebertaVaTokenizer(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) a__ : Optional[int] = DebertaVaTokenizerFast(lowerCamelCase__ , keep_accents=lowerCamelCase__ ) a__ : List[Any] = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : List[Any] = tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Dict = tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Optional[int] = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Union[str, Any] = rust_tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) # fmt: off a__ : Tuple = "I was born in 92000, and this is falsé." a__ : List[Any] = [13, 1, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9] a__ : str = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] a__ : Union[str, Any] = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on a__ : Union[str, Any] = tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Tuple = tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Optional[Any] = tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : List[str] = rust_tokenizer.encode(lowerCamelCase__ , add_special_tokens=lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : List[Any] = rust_tokenizer.tokenize(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) a__ : Dict = rust_tokenizer.convert_ids_to_tokens(lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) def _UpperCamelCase( self : Optional[Any] ): a__ : str = DebertaVaTokenizer(lowerCamelCase__ ) a__ : int = tokenizer.encode("sequence builders" ) a__ : Optional[int] = tokenizer.encode("multi-sequence build" ) a__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(lowerCamelCase__ ) a__ : Any = tokenizer.build_inputs_with_special_tokens(lowerCamelCase__ , lowerCamelCase__ ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , lowerCamelCase__ ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , lowerCamelCase__ , ) @slow def _UpperCamelCase( self : Union[str, Any] ): # fmt: off a__ : str = {"input_ids": [[1, 39_867, 36, 19_390, 486, 27, 35_052, 81_436, 18, 60_685, 1_225, 7, 35_052, 81_436, 18, 9_367, 16_899, 18, 15_937, 53, 594, 773, 18, 16_287, 30_465, 36, 15_937, 6, 41_139, 38, 36_979, 60_763, 191, 6, 34_132, 99, 6, 50_538, 390, 43_230, 6, 34_132, 2_779, 20_850, 14, 699, 1_072, 1_194, 36, 382, 10_901, 53, 7, 699, 1_072, 2_084, 36, 20_422, 630, 53, 19, 105, 3_049, 1_896, 1_053, 16_899, 1_506, 11, 37_978, 4_243, 7, 1_237, 31_869, 200, 16_566, 654, 6, 35_052, 81_436, 7, 55_630, 13_593, 4, 2], [1, 26, 15_011, 13, 667, 8, 1_053, 18, 23_611, 1_237, 72_356, 12_820, 34, 104_134, 1_209, 35, 13_313, 6_627, 21, 202, 347, 7, 164, 2_399, 11, 46, 4_485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1_232, 2_864, 15_785, 14_951, 105, 5, 8_581, 1_250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCamelCase__ , model_name="microsoft/deberta-v2-xlarge" , revision="ad6e42c1532ddf3a15c39246b63f5559d558b670" , )
37
_snake_case : Optional[int] = {"a": ["c", "b"], "b": ["d", "e"], "c": [], "d": [], "e": []} _snake_case : Dict = ["a", "b", "c", "d", "e"] def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): __snake_case : List[str] = start # add current to visited visited.append(__lowerCamelCase ) __snake_case : List[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __snake_case : Tuple = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # if all neighbors visited add current to sort sort.append(__lowerCamelCase ) # if all vertices haven't been visited select a new one to visit if len(__lowerCamelCase ) != len(__lowerCamelCase ): for vertice in vertices: if vertice not in visited: __snake_case : int = topological_sort(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) # return sort return sort if __name__ == "__main__": _snake_case : List[Any] = topological_sort("a", [], []) print(sort)
81
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings from diffusers.utils import load_numpy, slow, torch_device from diffusers.utils.testing_utils import require_torch_gpu A_ : int = False class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __UpperCamelCase ( self ): return 1_2 @property def __UpperCamelCase ( self ): return 1_2 @property def __UpperCamelCase ( self ): return 3_2 @property def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : List[Any] = VQModel( 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=3 , num_vq_embeddings=self.num_embed , vq_embed_dim=3 , ) return model @property def __UpperCamelCase ( self ): snake_case__ : List[Any] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModel(__SCREAMING_SNAKE_CASE ) @property def __UpperCamelCase ( self ): torch.manual_seed(0 ) snake_case__ : Any = 1_2 snake_case__ : Any = 1_2 snake_case__ : Any = { """attention_bias""": True, """cross_attention_dim""": 3_2, """attention_head_dim""": height * width, """num_attention_heads""": 1, """num_vector_embeds""": self.num_embed, """num_embeds_ada_norm""": self.num_embeds_ada_norm, """norm_num_groups""": 3_2, """sample_size""": width, """activation_fn""": """geglu-approximate""", } snake_case__ : int = TransformeraDModel(**__SCREAMING_SNAKE_CASE ) return model def __UpperCamelCase ( self ): snake_case__ : Optional[int] = """cpu""" snake_case__ : int = self.dummy_vqvae snake_case__ : Union[str, Any] = self.dummy_text_encoder snake_case__ : str = self.dummy_tokenizer snake_case__ : List[Any] = self.dummy_transformer snake_case__ : Union[str, Any] = VQDiffusionScheduler(self.num_embed ) snake_case__ : Tuple = LearnedClassifierFreeSamplingEmbeddings(learnable=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = VQDiffusionPipeline( vqvae=__SCREAMING_SNAKE_CASE , text_encoder=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , transformer=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=__SCREAMING_SNAKE_CASE , ) snake_case__ : List[str] = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : Any = """teddy bear playing in the pool""" snake_case__ : Union[str, Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) snake_case__ : Union[str, Any] = pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" ) snake_case__ : List[Any] = output.images snake_case__ : str = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) snake_case__ : Optional[int] = pipe( [prompt] , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=__SCREAMING_SNAKE_CASE , num_inference_steps=2 )[0] snake_case__ : Optional[int] = image[0, -3:, -3:, -1] snake_case__ : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) snake_case__ : List[Any] = np.array([0.6551, 0.6168, 0.5008, 0.5676, 0.5659, 0.4295, 0.6073, 0.5599, 0.4992] ) 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 ): snake_case__ : int = """cpu""" snake_case__ : Optional[Any] = self.dummy_vqvae snake_case__ : Optional[int] = self.dummy_text_encoder snake_case__ : List[Any] = self.dummy_tokenizer snake_case__ : List[str] = self.dummy_transformer snake_case__ : Tuple = VQDiffusionScheduler(self.num_embed ) snake_case__ : Dict = LearnedClassifierFreeSamplingEmbeddings( learnable=__SCREAMING_SNAKE_CASE , hidden_size=self.text_embedder_hidden_size , length=tokenizer.model_max_length ) snake_case__ : Union[str, Any] = VQDiffusionPipeline( vqvae=__SCREAMING_SNAKE_CASE , text_encoder=__SCREAMING_SNAKE_CASE , tokenizer=__SCREAMING_SNAKE_CASE , transformer=__SCREAMING_SNAKE_CASE , scheduler=__SCREAMING_SNAKE_CASE , learned_classifier_free_sampling_embeddings=__SCREAMING_SNAKE_CASE , ) snake_case__ : Any = pipe.to(__SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) snake_case__ : List[str] = """teddy bear playing in the pool""" snake_case__ : Optional[Any] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) snake_case__ : Optional[Any] = pipe([prompt] , generator=__SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="""np""" ) snake_case__ : int = output.images snake_case__ : int = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) snake_case__ : Any = pipe( [prompt] , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , return_dict=__SCREAMING_SNAKE_CASE , num_inference_steps=2 )[0] snake_case__ : Optional[Any] = image[0, -3:, -3:, -1] snake_case__ : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 2_4, 2_4, 3) snake_case__ : Optional[Any] = np.array([0.6693, 0.6075, 0.4959, 0.5701, 0.5583, 0.4333, 0.6171, 0.5684, 0.4988] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2.0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self ): snake_case__ : Optional[int] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy""" ) snake_case__ : Dict = VQDiffusionPipeline.from_pretrained("""microsoft/vq-diffusion-ithq""" ) snake_case__ : int = pipeline.to(__SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE ) # requires GPU generator for gumbel softmax # don't use GPU generator in tests though snake_case__ : List[str] = torch.Generator(device=__SCREAMING_SNAKE_CASE ).manual_seed(0 ) snake_case__ : List[str] = pipeline( """teddy bear playing in the pool""" , num_images_per_prompt=1 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , ) snake_case__ : Any = output.images[0] assert image.shape == (2_5_6, 2_5_6, 3) assert np.abs(expected_image - image ).max() < 2.0
38
def lowerCAmelCase_ ( ): return [ a * b * (1_0_0_0 - a - b) for a in range(1 , 9_9_9 ) for b in range(__lowerCamelCase , 9_9_9 ) if (a * a + b * b == (1_0_0_0 - a - b) ** 2) ][0] if __name__ == "__main__": print(f'''{solution() = }''')
81
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class snake_case_ ( __A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = "dpr" def __init__( self : str , _UpperCamelCase : str=3_0_5_2_2 , _UpperCamelCase : Optional[Any]=7_6_8 , _UpperCamelCase : Any=1_2 , _UpperCamelCase : Optional[Any]=1_2 , _UpperCamelCase : Dict=3_0_7_2 , _UpperCamelCase : Dict="gelu" , _UpperCamelCase : Tuple=0.1 , _UpperCamelCase : Dict=0.1 , _UpperCamelCase : Union[str, Any]=5_1_2 , _UpperCamelCase : int=2 , _UpperCamelCase : Union[str, Any]=0.02 , _UpperCamelCase : Union[str, Any]=1e-12 , _UpperCamelCase : List[str]=0 , _UpperCamelCase : int="absolute" , _UpperCamelCase : int = 0 , **_UpperCamelCase : List[Any] , ) ->Union[str, Any]: super().__init__(pad_token_id=_UpperCamelCase , **_UpperCamelCase ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = projection_dim snake_case_ = position_embedding_type
39
from math import sqrt def lowerCAmelCase_ ( __lowerCamelCase = 1_0_0_0_0_0_0 ): __snake_case : int = 0 __snake_case : int = 0 __snake_case : int while num_cuboids <= limit: max_cuboid_size += 1 for sum_shortest_sides in range(2 , 2 * max_cuboid_size + 1 ): if sqrt(sum_shortest_sides**2 + max_cuboid_size**2 ).is_integer(): num_cuboids += ( min(__lowerCamelCase , sum_shortest_sides // 2 ) - max(1 , sum_shortest_sides - max_cuboid_size ) + 1 ) return max_cuboid_size if __name__ == "__main__": print(f'''{solution() = }''')
81
0