code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' def __UpperCAmelCase ( __magic_name__ )-> Union[str, Any]: """simple docstring""" if isinstance(lowerCAmelCase_ ,lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ ,lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" snake_case_ : Union[str, Any] = False if num < 0: snake_case_ : Dict = True snake_case_ : Union[str, Any] = -num snake_case_ : Dict = [] while num > 0: binary.insert(0 ,num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
653
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class lowerCAmelCase_ ( UpperCamelCase__ ): __lowerCamelCase : Tuple = "gpt_neo" __lowerCamelCase : List[Any] = ["past_key_values"] __lowerCamelCase : Optional[Any] = {"num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"} def __init__( self , _lowerCAmelCase=50257 , _lowerCAmelCase=2048 , _lowerCAmelCase=2048 , _lowerCAmelCase=24 , _lowerCAmelCase=[[["global", "local"], 12]] , _lowerCAmelCase=16 , _lowerCAmelCase=None , _lowerCAmelCase=256 , _lowerCAmelCase="gelu_new" , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.0 , _lowerCAmelCase=0.1 , _lowerCAmelCase=1E-5 , _lowerCAmelCase=0.02 , _lowerCAmelCase=True , _lowerCAmelCase=50256 , _lowerCAmelCase=50256 , **_lowerCAmelCase , ) -> List[str]: _lowerCAmelCase = vocab_size _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = hidden_size _lowerCAmelCase = num_layers _lowerCAmelCase = num_heads _lowerCAmelCase = intermediate_size _lowerCAmelCase = window_size _lowerCAmelCase = activation_function _lowerCAmelCase = resid_dropout _lowerCAmelCase = embed_dropout _lowerCAmelCase = attention_dropout _lowerCAmelCase = classifier_dropout _lowerCAmelCase = layer_norm_epsilon _lowerCAmelCase = initializer_range _lowerCAmelCase = use_cache _lowerCAmelCase = bos_token_id _lowerCAmelCase = eos_token_id _lowerCAmelCase = attention_types _lowerCAmelCase = self.expand_attention_types_params(SCREAMING_SNAKE_CASE__ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, ''' f'''`config.num_layers = {self.num_layers}`. ''' "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @staticmethod def _snake_case ( _lowerCAmelCase ) -> List[Any]: _lowerCAmelCase = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def __a(SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Union[str, Any] ): '''simple docstring''' import torch _lowerCAmelCase = input.size() _lowerCAmelCase = len(lowerCAmelCase_ ) _lowerCAmelCase = shape[dimension] _lowerCAmelCase = torch.arange(0 , lowerCAmelCase_ , lowerCAmelCase_ ) _lowerCAmelCase = torch.div(sizedim - size , lowerCAmelCase_ , rounding_mode="floor" ) + 1 _lowerCAmelCase = torch.arange(lowerCAmelCase_ ) + low_indices[:min_length][:, None] _lowerCAmelCase = [slice(lowerCAmelCase_ )] * rank _lowerCAmelCase = indices _lowerCAmelCase = input[s] _lowerCAmelCase = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(lowerCAmelCase_ ) def __a(SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple ): '''simple docstring''' import torch _lowerCAmelCase = torch.arange(1 , lowerCAmelCase_ ) _lowerCAmelCase = torch.remainder(lowerCAmelCase_ , lowerCAmelCase_ ) _lowerCAmelCase = remainders == 0 _lowerCAmelCase = candidates[divisor_indices] _lowerCAmelCase = torch.max(lowerCAmelCase_ ) return largest_divisor, torch.div(lowerCAmelCase_ , lowerCAmelCase_ , rounding_mode="floor" ) class lowerCAmelCase_ ( UpperCamelCase__ ): @property def _snake_case ( self ) -> Mapping[str, Mapping[int, str]]: _lowerCAmelCase = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__ , direction="inputs" ) _lowerCAmelCase = {0: "batch", 1: "past_sequence + sequence"} else: _lowerCAmelCase = {0: "batch", 1: "sequence"} return common_inputs @property def _snake_case ( self ) -> int: return self._config.num_heads def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = -1 , _lowerCAmelCase = -1 , _lowerCAmelCase = False , _lowerCAmelCase = None , ) -> Mapping[str, Any]: _lowerCAmelCase = super(SCREAMING_SNAKE_CASE__ , self ).generate_dummy_inputs( SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) # We need to order the input in the way they appears in the forward() _lowerCAmelCase = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch _lowerCAmelCase , _lowerCAmelCase = common_inputs["input_ids"].shape # Not using the same length for past_key_values _lowerCAmelCase = seqlen + 2 _lowerCAmelCase = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) _lowerCAmelCase = [ (torch.zeros(SCREAMING_SNAKE_CASE__ ), torch.zeros(SCREAMING_SNAKE_CASE__ )) for _ in range(self.num_layers ) ] _lowerCAmelCase = common_inputs["attention_mask"] if self.use_past: _lowerCAmelCase = ordered_inputs["attention_mask"].dtype _lowerCAmelCase = torch.cat( [ordered_inputs["attention_mask"], torch.ones(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ )] , dim=1 ) return ordered_inputs @property def _snake_case ( self ) -> int: return 13
18
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
"""simple docstring""" 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 _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self , _lowercase , _lowercase = True , _lowercase = None , _lowercase = 32 , _lowercase = True , _lowercase = 1 / 255 , _lowercase = True , _lowercase = True , _lowercase = [0.48145466, 0.4578275, 0.40821073] , _lowercase = [0.26862954, 0.26130258, 0.27577711] , _lowercase = True , _lowercase=7 , _lowercase=30 , _lowercase=400 , _lowercase=3 , ) -> Tuple: _lowerCamelCase : Union[str, Any] = parent _lowerCamelCase : List[Any] = do_resize _lowerCamelCase : Optional[Any] = size if size is not None else {'''shortest_edge''': 288} _lowerCamelCase : int = size_divisor _lowerCamelCase : int = do_rescale _lowerCamelCase : List[Any] = rescale_factor _lowerCamelCase : List[Any] = do_normalize _lowerCamelCase : Tuple = do_center_crop _lowerCamelCase : Optional[Any] = image_mean _lowerCamelCase : Union[str, Any] = image_std _lowerCamelCase : Dict = do_pad _lowerCamelCase : Any = batch_size _lowerCamelCase : Union[str, Any] = num_channels _lowerCamelCase : Tuple = min_resolution _lowerCamelCase : Optional[int] = max_resolution def a__ ( self ) -> Tuple: 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 a__ ( self , _lowercase , _lowercase=False ) -> Optional[Any]: if not batched: _lowerCamelCase : List[str] = self.size['''shortest_edge'''] _lowerCamelCase : List[str] = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): _lowerCamelCase, _lowerCamelCase : Optional[Any] = image.size else: _lowerCamelCase, _lowerCamelCase : List[Any] = image.shape[1], image.shape[2] _lowerCamelCase : Optional[Any] = size / min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if h < w: _lowerCamelCase, _lowerCamelCase : List[str] = size, scale * w else: _lowerCamelCase, _lowerCamelCase : int = scale * h, size _lowerCamelCase : Union[str, Any] = int((1333 / 800) * size ) if max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) > max_size: _lowerCamelCase : Any = max_size / max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = newh * scale _lowerCamelCase : Any = neww * scale _lowerCamelCase, _lowerCamelCase : List[str] = int(newh + 0.5 ), int(neww + 0.5 ) _lowerCamelCase, _lowerCamelCase : str = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: _lowerCamelCase : Dict = [] for image in image_inputs: _lowerCamelCase, _lowerCamelCase : Any = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ , key=lambda _lowercase : item[0] )[0] _lowerCamelCase : Dict = max(SCREAMING_SNAKE_CASE__ , key=lambda _lowercase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _UpperCAmelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" __snake_case = BridgeTowerImageProcessor if is_vision_available() else None def a__ ( self ) -> int: _lowerCamelCase : Any = BridgeTowerImageProcessingTester(self ) @property def a__ ( self ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ) -> Dict: _lowerCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''image_mean''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''image_std''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''size_divisor''' ) ) def a__ ( self ) -> Tuple: pass def a__ ( self ) -> Any: # Initialize image processor _lowerCamelCase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _lowerCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input _lowerCamelCase : int = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Tuple = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ) -> List[Any]: # Initialize image processor _lowerCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _lowerCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input _lowerCamelCase : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Any = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCamelCase : str = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ) -> Tuple: # Initialize image processor _lowerCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _lowerCamelCase : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input _lowerCamelCase : Optional[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _lowerCamelCase : List[str] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _lowerCamelCase, _lowerCamelCase : Optional[Any] = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
434
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _snake_case = logging.get_logger(__name__) if is_vision_available(): import PIL class _SCREAMING_SNAKE_CASE ( UpperCamelCase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE_: Any = ["pixel_values"] def __init__( self : Optional[int] , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Union[str, Any] , ) -> None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = size if size is not None else {'shortest_edge': 224} _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = crop_size if crop_size is not None else {'height': 224, 'width': 224} _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ , param_name='crop_size' ) _lowerCAmelCase = do_resize _lowerCAmelCase = size _lowerCAmelCase = resample _lowerCAmelCase = do_center_crop _lowerCAmelCase = crop_size _lowerCAmelCase = do_rescale _lowerCAmelCase = rescale_factor _lowerCAmelCase = do_normalize _lowerCAmelCase = image_mean if image_mean is not None else OPENAI_CLIP_MEAN _lowerCAmelCase = image_std if image_std is not None else OPENAI_CLIP_STD _lowerCAmelCase = do_convert_rgb def __lowerCamelCase ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Union[str, Any] , ) -> np.ndarray: """simple docstring""" _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}""" ) _lowerCAmelCase = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size['shortest_edge'] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self : int , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ) -> np.ndarray: """simple docstring""" _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(F"""The `size` parameter must contain the keys (height, width). Got {size.keys()}""" ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size['height'], size['width']) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Tuple , ) -> str: """simple docstring""" return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self : str , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Optional[int] , ) -> np.ndarray: """simple docstring""" return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self : List[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCAmelCase_ : List[Any] , ) -> PIL.Image.Image: """simple docstring""" _lowerCAmelCase = do_resize if do_resize is not None else self.do_resize _lowerCAmelCase = size if size is not None else self.size _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='size' , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = resample if resample is not None else self.resample _lowerCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _lowerCAmelCase = crop_size if crop_size is not None else self.crop_size _lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='crop_size' , default_to_square=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _lowerCAmelCase = image_mean if image_mean is not None else self.image_mean _lowerCAmelCase = image_std if image_std is not None else self.image_std _lowerCAmelCase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb _lowerCAmelCase = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: _lowerCAmelCase = [convert_to_rgb(SCREAMING_SNAKE_CASE__ ) for image in images] # All transformations expect numpy arrays. _lowerCAmelCase = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: _lowerCAmelCase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: _lowerCAmelCase = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: _lowerCAmelCase = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: _lowerCAmelCase = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] _lowerCAmelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] _lowerCAmelCase = {'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
580
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version _UpperCAmelCase = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' lowerCamelCase_ = '''dummy_data''' lowerCamelCase_ = '''datasets''' lowerCamelCase_ = False def __init__( self , lowercase , lowercase , lowercase , lowercase = None , lowercase = False , lowercase = True , lowercase = None , ): """simple docstring""" A_ : List[Any] = 0 A_ : Optional[int] = dataset_name A_ : Dict = cache_dir A_ : List[str] = use_local_dummy_data A_ : Dict = config # download_callbacks take a single url as input A_ : Optional[int] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root A_ : List[Any] = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general A_ : Dict = str(SCREAMING_SNAKE_CASE__ ) # to be downloaded A_ : Optional[Any] = None A_ : Union[str, Any] = None @property def lowerCAmelCase_ ( self ): """simple docstring""" if self._dummy_file is None: A_ : Union[str, Any] = self.download_dummy_data() return self._dummy_file @property def lowerCAmelCase_ ( self ): """simple docstring""" if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('dummy' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('dummy' , self.version_name ) @property def lowerCAmelCase_ ( self ): """simple docstring""" return os.path.join(self.dummy_data_folder , 'dummy_data.zip' ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Any = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) A_ : Optional[Any] = cached_path( SCREAMING_SNAKE_CASE__ , cache_dir=self.cache_dir , extract_compressed_file=SCREAMING_SNAKE_CASE__ , force_extract=SCREAMING_SNAKE_CASE__ ) return os.path.join(SCREAMING_SNAKE_CASE__ , self.dummy_file_name ) @property def lowerCAmelCase_ ( self ): """simple docstring""" return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def lowerCAmelCase_ ( self ): """simple docstring""" if self._bucket_url is None: A_ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '/' ) ) return self._bucket_url @property def lowerCAmelCase_ ( self ): """simple docstring""" if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '/' ).split('/' )[:-1] ) def lowerCAmelCase_ ( self , lowercase , *lowercase ): """simple docstring""" if self.load_existing_dummy_data: # dummy data is downloaded and tested A_ : Dict = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned A_ : List[str] = self.dummy_file_name # special case when data_url is a dict if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return self.create_dummy_data_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): return self.create_dummy_data_list(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: return self.create_dummy_data_single(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self , lowercase , *lowercase ): """simple docstring""" return self.download_and_extract(SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self , lowercase , lowercase ): """simple docstring""" return self.download_and_extract(SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self , lowercase , *lowercase , **lowercase ): """simple docstring""" return path def lowerCAmelCase_ ( self ): """simple docstring""" return {} def lowerCAmelCase_ ( self , lowercase , lowercase ): """simple docstring""" A_ : Optional[int] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for single_url in single_urls: download_callback(SCREAMING_SNAKE_CASE__ ) else: A_ : int = single_urls download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A_ : int = [os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(Path(SCREAMING_SNAKE_CASE__ ).name ) ) for x in single_urls] else: A_ : Optional[int] = single_urls A_ : Optional[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(Path(SCREAMING_SNAKE_CASE__ ).name ) ) A_ : Optional[int] = value # make sure that values are unique if all(isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique A_ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowerCAmelCase_ ( self , lowercase , lowercase ): """simple docstring""" A_ : List[Any] = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one A_ : Union[str, Any] = all(bool(re.findall('[0-9]{3,}-of-[0-9]{3,}' , SCREAMING_SNAKE_CASE__ ) ) for url in data_url ) A_ : Dict = all( url.startswith('https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): A_ : List[str] = [data_url[0]] * len(SCREAMING_SNAKE_CASE__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus A_ : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(single_url.split('/' )[-1] ) ) dummy_data_list.append(SCREAMING_SNAKE_CASE__ ) return dummy_data_list def lowerCAmelCase_ ( self , lowercase , lowercase ): """simple docstring""" for download_callback in self.download_callbacks: download_callback(SCREAMING_SNAKE_CASE__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus A_ : Union[str, Any] = os.path.join(SCREAMING_SNAKE_CASE__ , urllib.parse.quote_plus(data_url.split('/' )[-1] ) ) if os.path.exists(SCREAMING_SNAKE_CASE__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowerCAmelCase_ ( self ): """simple docstring""" pass def lowerCAmelCase_ ( self ): """simple docstring""" pass def lowerCAmelCase_ ( self , lowercase ): """simple docstring""" def _iter_archive_members(lowercase ): # this preserves the order of the members inside the ZIP archive A_ : Any = Path(self.dummy_file ).parent A_ : List[Any] = path.relative_to(SCREAMING_SNAKE_CASE__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: A_ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(SCREAMING_SNAKE_CASE__ ) A_ : List[Any] = Path(SCREAMING_SNAKE_CASE__ ) A_ : Union[str, Any] = _iter_archive_members(SCREAMING_SNAKE_CASE__ ) if self.use_local_dummy_data else path.rglob('*' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('.', '__') ): yield file_path.relative_to(SCREAMING_SNAKE_CASE__ ).as_posix(), file_path.open('rb' ) def lowerCAmelCase_ ( self , lowercase ): """simple docstring""" if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A_ : List[Any] = [paths] for path in paths: if os.path.isfile(SCREAMING_SNAKE_CASE__ ): if os.path.basename(SCREAMING_SNAKE_CASE__ ).startswith(('.', '__') ): return yield path else: for dirpath, dirnames, filenames in os.walk(SCREAMING_SNAKE_CASE__ ): if os.path.basename(SCREAMING_SNAKE_CASE__ ).startswith(('.', '__') ): continue dirnames.sort() for filename in sorted(SCREAMING_SNAKE_CASE__ ): if filename.startswith(('.', '__') ): continue yield os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
558
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
"""simple docstring""" 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 lowercase ( UpperCamelCase__ ): lowercase = '''char''' lowercase = '''bpe''' lowercase = '''wp''' UpperCAmelCase = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class lowercase ( UpperCamelCase__ ): lowercase = ['''image_processor''', '''char_tokenizer'''] lowercase = '''ViTImageProcessor''' lowercase = '''MgpstrTokenizer''' def __init__(self : Any ,SCREAMING_SNAKE_CASE_ : Dict=None ,SCREAMING_SNAKE_CASE_ : int=None ,**SCREAMING_SNAKE_CASE_ : str ) -> str: """simple docstring""" lowerCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' ,SCREAMING_SNAKE_CASE__ ,) lowerCAmelCase = kwargs.pop('''feature_extractor''' ) lowerCAmelCase = 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`.''' ) lowerCAmelCase = tokenizer lowerCAmelCase = AutoTokenizer.from_pretrained('''gpt2''' ) lowerCAmelCase = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ) def __call__(self : List[str] ,SCREAMING_SNAKE_CASE_ : List[str]=None ,SCREAMING_SNAKE_CASE_ : Any=None ,SCREAMING_SNAKE_CASE_ : Union[str, Any]=None ,**SCREAMING_SNAKE_CASE_ : Dict ) -> Dict: """simple docstring""" 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: lowerCAmelCase = self.image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) if text is not None: lowerCAmelCase = self.char_tokenizer(SCREAMING_SNAKE_CASE__ ,return_tensors=SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ ) if text is None: return inputs elif images is None: return encodings else: lowerCAmelCase = encodings['''input_ids'''] return inputs def UpperCAmelCase (self : Optional[int] ,SCREAMING_SNAKE_CASE_ : List[str] ) -> Any: """simple docstring""" lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = sequences lowerCAmelCase = char_preds.size(0 ) lowerCAmelCase , lowerCAmelCase = self._decode_helper(SCREAMING_SNAKE_CASE__ ,'''char''' ) lowerCAmelCase , lowerCAmelCase = self._decode_helper(SCREAMING_SNAKE_CASE__ ,'''bpe''' ) lowerCAmelCase , lowerCAmelCase = self._decode_helper(SCREAMING_SNAKE_CASE__ ,'''wp''' ) lowerCAmelCase = [] lowerCAmelCase = [] for i in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase = [char_scores[i], bpe_scores[i], wp_scores[i]] lowerCAmelCase = [char_strs[i], bpe_strs[i], wp_strs[i]] lowerCAmelCase = scores.index(max(SCREAMING_SNAKE_CASE__ ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) lowerCAmelCase = {} lowerCAmelCase = final_strs lowerCAmelCase = final_scores lowerCAmelCase = char_strs lowerCAmelCase = bpe_strs lowerCAmelCase = wp_strs return out def UpperCAmelCase (self : List[Any] ,SCREAMING_SNAKE_CASE_ : Tuple ,SCREAMING_SNAKE_CASE_ : Tuple ) -> str: """simple docstring""" if format == DecodeType.CHARACTER: lowerCAmelCase = self.char_decode lowerCAmelCase = 1 lowerCAmelCase = '''[s]''' elif format == DecodeType.BPE: lowerCAmelCase = self.bpe_decode lowerCAmelCase = 2 lowerCAmelCase = '''#''' elif format == DecodeType.WORDPIECE: lowerCAmelCase = self.wp_decode lowerCAmelCase = 102 lowerCAmelCase = '''[SEP]''' else: raise ValueError(F"""Format {format} is not supported.""" ) lowerCAmelCase , lowerCAmelCase = [], [] lowerCAmelCase = pred_logits.size(0 ) lowerCAmelCase = pred_logits.size(1 ) lowerCAmelCase , lowerCAmelCase = pred_logits.topk(1 ,dim=-1 ,largest=SCREAMING_SNAKE_CASE__ ,sorted=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = preds_index.view(-1 ,SCREAMING_SNAKE_CASE__ )[:, 1:] lowerCAmelCase = decoder(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase , lowerCAmelCase = torch.nn.functional.softmax(SCREAMING_SNAKE_CASE__ ,dim=2 ).max(dim=2 ) lowerCAmelCase = preds_max_prob[:, 1:] for index in range(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase = preds_str[index].find(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = preds_str[index][:pred_eos] lowerCAmelCase = preds_index[index].cpu().tolist() lowerCAmelCase = pred_index.index(SCREAMING_SNAKE_CASE__ ) if eos_token in pred_index else -1 lowerCAmelCase = preds_max_prob[index][: pred_eos_index + 1] lowerCAmelCase = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(SCREAMING_SNAKE_CASE__ ) conf_scores.append(SCREAMING_SNAKE_CASE__ ) return dec_strs, conf_scores def UpperCAmelCase (self : Union[str, Any] ,SCREAMING_SNAKE_CASE_ : Any ) -> Dict: """simple docstring""" lowerCAmelCase = [seq.replace(''' ''' ,'''''' ) for seq in self.char_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs def UpperCAmelCase (self : Any ,SCREAMING_SNAKE_CASE_ : int ) -> Optional[int]: """simple docstring""" return self.bpe_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase (self : Tuple ,SCREAMING_SNAKE_CASE_ : str ) -> List[Any]: """simple docstring""" lowerCAmelCase = [seq.replace(''' ''' ,'''''' ) for seq in self.wp_tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )] return decode_strs
535
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
import warnings from ...utils import logging from .image_processing_dpt import DPTImageProcessor __UpperCamelCase : Optional[int] = logging.get_logger(__name__) class __UpperCamelCase ( UpperCamelCase__ ): def __init__( self : str , *_lowerCAmelCase : int , **_lowerCAmelCase : Any ) -> None: """simple docstring""" warnings.warn( """The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DPTImageProcessor instead.""" , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
80
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = 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 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
'''simple docstring''' import json import os import unittest from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class UpperCAmelCase__ ( UpperCamelCase__ , unittest.TestCase ): lowerCAmelCase_ = LEDTokenizer lowerCAmelCase_ = LEDTokenizerFast lowerCAmelCase_ = True def lowerCamelCase_ ( self : int ): super().setUp() _lowerCamelCase : Tuple = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] _lowerCamelCase : Tuple = dict(zip(SCREAMING_SNAKE_CASE__,range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) _lowerCamelCase : List[str] = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] _lowerCamelCase : List[Any] = {"unk_token": "<unk>"} _lowerCamelCase : Union[str, Any] = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["vocab_file"] ) _lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["merges_file"] ) with open(self.vocab_file,"w",encoding="utf-8" ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE__ ) + "\n" ) with open(self.merges_file,"w",encoding="utf-8" ) as fp: fp.write("\n".join(SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase_ ( self : List[str],**__A : int ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname,**SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : List[Any],**__A : List[str] ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname,**SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : Tuple,__A : Any ): return "lower newer", "lower newer" @cached_property def lowerCamelCase_ ( self : int ): return LEDTokenizer.from_pretrained("allenai/led-base-16384" ) @cached_property def lowerCamelCase_ ( self : Dict ): return LEDTokenizerFast.from_pretrained("allenai/led-base-16384" ) @require_torch def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : str = ["A long paragraph for summarization.", "Another paragraph for summarization."] _lowerCamelCase : Union[str, Any] = [0, 2_5_0, 2_5_1, 1_7_8_1_8, 1_3, 3_9_1_8_6, 1_9_3_8, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : Union[str, Any] = tokenizer(SCREAMING_SNAKE_CASE__,max_length=len(SCREAMING_SNAKE_CASE__ ),padding=SCREAMING_SNAKE_CASE__,return_tensors="pt" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 9),batch.input_ids.shape ) self.assertEqual((2, 9),batch.attention_mask.shape ) _lowerCamelCase : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) @require_torch def lowerCamelCase_ ( self : Union[str, Any] ): _lowerCamelCase : Optional[Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : List[str] = tokenizer(SCREAMING_SNAKE_CASE__,padding=SCREAMING_SNAKE_CASE__,return_tensors="pt" ) self.assertIn("input_ids",SCREAMING_SNAKE_CASE__ ) self.assertIn("attention_mask",SCREAMING_SNAKE_CASE__ ) self.assertNotIn("labels",SCREAMING_SNAKE_CASE__ ) self.assertNotIn("decoder_attention_mask",SCREAMING_SNAKE_CASE__ ) @require_torch def lowerCamelCase_ ( self : List[Any] ): _lowerCamelCase : Union[str, Any] = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : Optional[int] = tokenizer(text_target=SCREAMING_SNAKE_CASE__,max_length=3_2,padding="max_length",return_tensors="pt" ) self.assertEqual(3_2,targets["input_ids"].shape[1] ) @require_torch def lowerCamelCase_ ( self : int ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : Optional[int] = tokenizer( ["I am a small frog" * 1_0_2_4, "I am a small frog"],padding=SCREAMING_SNAKE_CASE__,truncation=SCREAMING_SNAKE_CASE__,return_tensors="pt" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) self.assertEqual(batch.input_ids.shape,(2, 5_1_2_2) ) @require_torch def lowerCamelCase_ ( self : str ): _lowerCamelCase : Union[str, Any] = ["A long paragraph for summarization."] _lowerCamelCase : Tuple = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : str = tokenizer(SCREAMING_SNAKE_CASE__,return_tensors="pt" ) _lowerCamelCase : Any = tokenizer(text_target=SCREAMING_SNAKE_CASE__,return_tensors="pt" ) _lowerCamelCase : List[Any] = inputs["input_ids"] _lowerCamelCase : Dict = targets["input_ids"] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) @require_torch def lowerCamelCase_ ( self : Any ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: _lowerCamelCase : str = ["Summary of the text.", "Another summary."] _lowerCamelCase : Dict = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]] _lowerCamelCase : List[str] = tokenizer(SCREAMING_SNAKE_CASE__,padding=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[Any] = [[0] * len(SCREAMING_SNAKE_CASE__ ) for x in encoded_output["input_ids"]] _lowerCamelCase : List[str] = tokenizer.pad(SCREAMING_SNAKE_CASE__ ) self.assertSequenceEqual(outputs["global_attention_mask"],SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : Any ): pass def lowerCamelCase_ ( self : str ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): _lowerCamelCase : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Any = self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__,**SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : str = "A, <mask> AllenNLP sentence." _lowerCamelCase : Optional[int] = tokenizer_r.encode_plus(SCREAMING_SNAKE_CASE__,add_special_tokens=SCREAMING_SNAKE_CASE__,return_token_type_ids=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = tokenizer_p.encode_plus(SCREAMING_SNAKE_CASE__,add_special_tokens=SCREAMING_SNAKE_CASE__,return_token_type_ids=SCREAMING_SNAKE_CASE__ ) self.assertEqual(sum(tokens_r["token_type_ids"] ),sum(tokens_p["token_type_ids"] ) ) self.assertEqual( sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ),sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ),) _lowerCamelCase : int = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) _lowerCamelCase : int = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] ) self.assertSequenceEqual(tokens_p["input_ids"],[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual(tokens_r["input_ids"],[0, 2_5_0, 6, 5_0_2_6_4, 3_8_2_3, 4_8_7, 2_1_9_9_2, 3_6_4_5, 4, 2] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE__,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( SCREAMING_SNAKE_CASE__,["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
44
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
from __future__ import annotations import time import numpy as np snake_case_ = [8, 5, 9, 7] snake_case_ = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] snake_case_ = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class SCREAMING_SNAKE_CASE__ : def __init__( self , a , a , a , ): lowercase__ : Optional[Any] = claim_vector lowercase__ : Dict = allocated_resources_table lowercase__ : Tuple = maximum_claim_table def snake_case_ ( self): return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def snake_case_ ( self): return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation()) def snake_case_ ( self): return [ list(np.array(self.__maximum_claim_table[i]) - np.array(SCREAMING_SNAKE_CASE__)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def snake_case_ ( self): return {self.__need().index(SCREAMING_SNAKE_CASE__): i for i in self.__need()} def snake_case_ ( self , **a): lowercase__ : Optional[Any] = self.__need() lowercase__ : Optional[int] = self.__allocated_resources_table lowercase__ : Optional[int] = self.__available_resources() lowercase__ : Dict = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n') while need_list: lowercase__ : Optional[Any] = False for each_need in need_list: lowercase__ : Union[str, Any] = True for index, need in enumerate(SCREAMING_SNAKE_CASE__): if need > available_resources[index]: lowercase__ : Union[str, Any] = False break if execution: lowercase__ : Tuple = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: lowercase__ : Dict = original_need_index print(f"""Process {process_number + 1} is executing.""") # remove the process run from stack need_list.remove(SCREAMING_SNAKE_CASE__) # update available/freed resources stack lowercase__ : Optional[Any] = np.array(SCREAMING_SNAKE_CASE__) + np.array( alloc_resources_table[process_number]) print( 'Updated available resource stack for processes: ' + ' '.join([str(SCREAMING_SNAKE_CASE__) for x in available_resources])) break if safe: print('The process is in a safe state.\n') else: print('System in unsafe state. Aborting...\n') break def snake_case_ ( self): print(' ' * 9 + 'Allocated Resource Table') for item in self.__allocated_resources_table: print( f"""P{self.__allocated_resources_table.index(SCREAMING_SNAKE_CASE__) + 1}""" + ' '.join(f"""{it:>8}""" for it in item) + '\n') print(' ' * 9 + 'System Resource Table') for item in self.__maximum_claim_table: print( f"""P{self.__maximum_claim_table.index(SCREAMING_SNAKE_CASE__) + 1}""" + ' '.join(f"""{it:>8}""" for it in item) + '\n') print( 'Current Usage by Active Processes: ' + ' '.join(str(SCREAMING_SNAKE_CASE__) for x in self.__claim_vector)) print( 'Initial Available Resources: ' + ' '.join(str(SCREAMING_SNAKE_CASE__) for x in self.__available_resources())) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
164
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
"""simple docstring""" import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL a = logging.get_logger(__name__) def lowercase (snake_case__ : np.ndarray , snake_case__ : Union[int, Iterable[int]] , snake_case__ : bool , snake_case__ : int ) -> Union[str, Any]: '''simple docstring''' def constraint_to_multiple_of(snake_case__ : List[str] , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any]=0 , snake_case__ : List[Any]=None ): lowerCAmelCase = round(val / multiple ) * multiple if max_val is not None and x > max_val: lowerCAmelCase = math.floor(val / multiple ) * multiple if x < min_val: lowerCAmelCase = math.ceil(val / multiple ) * multiple return x lowerCAmelCase = (output_size, output_size) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) else output_size lowerCAmelCase , lowerCAmelCase = get_image_size(lowerCAmelCase_ ) lowerCAmelCase , lowerCAmelCase = output_size # determine new height and width lowerCAmelCase = output_height / input_height lowerCAmelCase = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width lowerCAmelCase = scale_width else: # fit height lowerCAmelCase = scale_height lowerCAmelCase = constraint_to_multiple_of(scale_height * input_height , multiple=lowerCAmelCase_ ) lowerCAmelCase = constraint_to_multiple_of(scale_width * input_width , multiple=lowerCAmelCase_ ) return (new_height, new_width) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): _a = ['pixel_values'] def __init__( self : Dict , lowerCAmelCase : bool = True , lowerCAmelCase : Dict[str, int] = None , lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , lowerCAmelCase : bool = False , lowerCAmelCase : int = 1 , lowerCAmelCase : bool = True , lowerCAmelCase : Union[int, float] = 1 / 255 , lowerCAmelCase : bool = True , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , **lowerCAmelCase : Optional[int] , ): super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = size if size is not None else {"""height""": 384, """width""": 384} lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = do_resize lowerCAmelCase = size lowerCAmelCase = keep_aspect_ratio lowerCAmelCase = ensure_multiple_of lowerCAmelCase = resample lowerCAmelCase = do_rescale lowerCAmelCase = rescale_factor lowerCAmelCase = do_normalize lowerCAmelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowercase ( self : Optional[int] , lowerCAmelCase : np.ndarray , lowerCAmelCase : Dict[str, int] , lowerCAmelCase : bool = False , lowerCAmelCase : int = 1 , lowerCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Dict , ): lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) lowerCAmelCase = get_resize_output_image_size( SCREAMING_SNAKE_CASE__ , output_size=(size["""height"""], size["""width"""]) , keep_aspect_ratio=SCREAMING_SNAKE_CASE__ , multiple=SCREAMING_SNAKE_CASE__ , ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowercase ( self : int , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[int, float] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : int , ): return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowercase ( self : str , lowerCAmelCase : np.ndarray , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Union[float, List[float]] , lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **lowerCAmelCase : Dict , ): return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowercase ( self : Dict , lowerCAmelCase : ImageInput , lowerCAmelCase : bool = None , lowerCAmelCase : int = None , lowerCAmelCase : bool = None , lowerCAmelCase : int = None , lowerCAmelCase : PILImageResampling = None , lowerCAmelCase : bool = None , lowerCAmelCase : float = None , lowerCAmelCase : bool = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[float, List[float]]] = None , lowerCAmelCase : Optional[Union[str, TensorType]] = None , lowerCAmelCase : ChannelDimension = ChannelDimension.FIRST , **lowerCAmelCase : int , ): lowerCAmelCase = do_resize if do_resize is not None else self.do_resize lowerCAmelCase = size if size is not None else self.size lowerCAmelCase = get_size_dict(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio lowerCAmelCase = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of lowerCAmelCase = resample if resample is not None else self.resample lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase = image_mean if image_mean is not None else self.image_mean lowerCAmelCase = image_std if image_std is not None else self.image_std lowerCAmelCase = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. lowerCAmelCase = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def __lowercase ( self : Union[str, Any] , lowerCAmelCase : Any , lowerCAmelCase : List[Tuple] = None ): lowerCAmelCase = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( """Make sure that you pass in as many target sizes as the batch dimension of the logits""" ) if is_torch_tensor(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase = target_sizes.numpy() lowerCAmelCase = [] for idx in range(len(SCREAMING_SNAKE_CASE__ ) ): lowerCAmelCase = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="""bilinear""" , align_corners=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase = logits.argmax(dim=1 ) lowerCAmelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
169
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0
from math import factorial def _a ( lowerCamelCase = 20 ): lowerCamelCase : Union[str, Any] = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... lowerCamelCase : List[Any] = n // 2 return int(factorial(lowerCAmelCase_ ) / (factorial(lowerCAmelCase_ ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(2_0)) else: try: _lowerCamelCase =int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
681
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCamelCase : str = logging.get_logger(__name__) __lowerCamelCase : Union[str, Any] = { '''vinvino02/glpn-kitti''': '''https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json''', # See all GLPN models at https://huggingface.co/models?filter=glpn } class A_ (UpperCamelCase__ ): """simple docstring""" a__ = '''glpn''' def __init__( self :Tuple , lowerCAmelCase__ :Any=3 , lowerCAmelCase__ :Tuple=4 , lowerCAmelCase__ :List[str]=[2, 2, 2, 2] , lowerCAmelCase__ :List[str]=[8, 4, 2, 1] , lowerCAmelCase__ :Union[str, Any]=[32, 64, 160, 256] , lowerCAmelCase__ :Any=[7, 3, 3, 3] , lowerCAmelCase__ :int=[4, 2, 2, 2] , lowerCAmelCase__ :Union[str, Any]=[1, 2, 5, 8] , lowerCAmelCase__ :str=[4, 4, 4, 4] , lowerCAmelCase__ :str="gelu" , lowerCAmelCase__ :int=0.0 , lowerCAmelCase__ :List[Any]=0.0 , lowerCAmelCase__ :Tuple=0.0_2 , lowerCAmelCase__ :Dict=0.1 , lowerCAmelCase__ :Optional[int]=1E-6 , lowerCAmelCase__ :List[Any]=64 , lowerCAmelCase__ :Optional[Any]=10 , lowerCAmelCase__ :Optional[int]=-1 , **lowerCAmelCase__ :int , ) -> Dict: '''simple docstring''' super().__init__(**SCREAMING_SNAKE_CASE__ ) snake_case_ : Dict = num_channels snake_case_ : List[Any] = num_encoder_blocks snake_case_ : Optional[int] = depths snake_case_ : List[str] = sr_ratios snake_case_ : Optional[Any] = hidden_sizes snake_case_ : Optional[int] = patch_sizes snake_case_ : str = strides snake_case_ : Union[str, Any] = mlp_ratios snake_case_ : Any = num_attention_heads snake_case_ : List[Any] = hidden_act snake_case_ : Union[str, Any] = hidden_dropout_prob snake_case_ : Optional[int] = attention_probs_dropout_prob snake_case_ : int = initializer_range snake_case_ : Any = drop_path_rate snake_case_ : Union[str, Any] = layer_norm_eps snake_case_ : int = decoder_hidden_size snake_case_ : Tuple = max_depth snake_case_ : Union[str, Any] = head_in_index
653
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
0
'''simple docstring''' def __a(SCREAMING_SNAKE_CASE_ : int = 10 , SCREAMING_SNAKE_CASE_ : int = 1000 , SCREAMING_SNAKE_CASE_ : bool = True ): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError("Invalid value for min_val or max_val (min_value < max_value)" ) return min_val if option else max_val def __a(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' return int((number_a + number_a) / 2 ) def __a(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ): '''simple docstring''' assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError("argument value for lower and higher must be(lower > higher)" ) if not lower < to_guess < higher: raise ValueError( "guess value must be within the range of lower and higher value" ) def answer(SCREAMING_SNAKE_CASE_ : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print("started..." ) _lowerCAmelCase = lower _lowerCAmelCase = higher _lowerCAmelCase = [] while True: _lowerCAmelCase = get_avg(lowerCAmelCase_ , lowerCAmelCase_ ) last_numbers.append(lowerCAmelCase_ ) if answer(lowerCAmelCase_ ) == "low": _lowerCAmelCase = number elif answer(lowerCAmelCase_ ) == "high": _lowerCAmelCase = number else: break print(F'''guess the number : {last_numbers[-1]}''' ) print(F'''details : {last_numbers!s}''' ) def __a(): '''simple docstring''' _lowerCAmelCase = int(input("Enter lower value : " ).strip() ) _lowerCAmelCase = int(input("Enter high value : " ).strip() ) _lowerCAmelCase = int(input("Enter value to guess : " ).strip() ) guess_the_number(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": main()
18
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
0
"""simple docstring""" def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Tuple: _lowerCamelCase : Optional[Any] = 0 for ch in input_str: _lowerCamelCase : str = ord(lowerCAmelCase_ ) _lowerCamelCase : Optional[Any] = pow(2 , lowerCAmelCase_ ) # If we already turned on bit for current character's unicode if bitmap >> ch_unicode & 1 == 1: return False bitmap |= ch_bit_index_on return True if __name__ == "__main__": import doctest doctest.testmod()
434
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
0
"""simple docstring""" import unittest from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow if is_flax_available(): import jax from transformers.models.auto.modeling_flax_auto import FlaxAutoModel from transformers.models.bert.modeling_flax_bert import FlaxBertModel from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel @require_flax class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCamelCase ( self : Dict ) -> List[Any]: """simple docstring""" for model_name in ["bert-base-cased", "bert-large-uncased"]: with self.subTest(SCREAMING_SNAKE_CASE__ ): _lowerCAmelCase = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def __lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" for model_name in ["roberta-base", "roberta-large"]: with self.subTest(SCREAMING_SNAKE_CASE__ ): _lowerCAmelCase = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def __lowerCamelCase ( self : List[Any] ) -> str: """simple docstring""" for model_name in ["bert-base-cased", "bert-large-uncased"]: _lowerCAmelCase = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = FlaxBertModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**UpperCAmelCase_ : Union[str, Any] ): return model(**SCREAMING_SNAKE_CASE__ ) eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready() @slow def __lowerCamelCase ( self : Tuple ) -> Any: """simple docstring""" for model_name in ["roberta-base", "roberta-large"]: _lowerCAmelCase = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = FlaxRobertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = tokenizer('Do you support jax jitted function?' , return_tensors=TensorType.JAX ) @jax.jit def eval(**UpperCAmelCase_ : Dict ): return model(**SCREAMING_SNAKE_CASE__ ) eval(**SCREAMING_SNAKE_CASE__ ).block_until_ready() def __lowerCamelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , 'bert-base is not a local folder and is not a valid model identifier' ): _lowerCAmelCase = FlaxAutoModel.from_pretrained('bert-base' ) def __lowerCamelCase ( self : Dict ) -> Dict: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): _lowerCAmelCase = FlaxAutoModel.from_pretrained(SCREAMING_SNAKE_CASE__ , revision='aaaaaa' ) def __lowerCamelCase ( self : Optional[Any] ) -> int: """simple docstring""" with self.assertRaisesRegex( SCREAMING_SNAKE_CASE__ , 'hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack' , ): _lowerCAmelCase = FlaxAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def __lowerCamelCase ( self : Dict ) -> Any: """simple docstring""" with self.assertRaisesRegex(SCREAMING_SNAKE_CASE__ , 'Use `from_pt=True` to load this model' ): _lowerCAmelCase = FlaxAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' )
580
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
0
import argparse from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import BigBirdPegasusConfig, BigBirdPegasusForConditionalGeneration _UpperCAmelCase = [ # tf -> hf ("""/""", """."""), ("""layer_""", """layers."""), ("""kernel""", """weight"""), ("""beta""", """bias"""), ("""gamma""", """weight"""), ("""pegasus""", """model"""), ] _UpperCAmelCase = [ (""".output.dense""", """.fc2"""), ("""intermediate.LayerNorm""", """final_layer_norm"""), ("""intermediate.dense""", """fc1"""), ] _UpperCAmelCase = ( INIT_COMMON + [ ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.out_proj"""), ("""attention.self""", """self_attn"""), ("""attention.encdec.LayerNorm""", """encoder_attn_layer_norm"""), ("""attention.encdec_output.dense""", """encoder_attn.out_proj"""), ("""attention.encdec""", """encoder_attn"""), ("""key""", """k_proj"""), ("""value""", """v_proj"""), ("""query""", """q_proj"""), ("""decoder.LayerNorm""", """decoder.layernorm_embedding"""), ] + END_COMMON ) _UpperCAmelCase = ( INIT_COMMON + [ ("""embeddings.word_embeddings""", """shared.weight"""), ("""embeddings.position_embeddings""", """embed_positions.weight"""), ("""attention.self.LayerNorm""", """self_attn_layer_norm"""), ("""attention.output.dense""", """self_attn.output"""), ("""attention.self""", """self_attn.self"""), ("""encoder.LayerNorm""", """encoder.layernorm_embedding"""), ] + END_COMMON ) _UpperCAmelCase = [ """encdec/key/bias""", """encdec/query/bias""", """encdec/value/bias""", """self/key/bias""", """self/query/bias""", """self/value/bias""", """encdec_output/dense/bias""", """attention/output/dense/bias""", ] def UpperCamelCase ( __lowercase : Optional[Any] ,__lowercase : Tuple ): '''simple docstring''' for tf_name, hf_name in patterns: A_ : int = k.replace(lowerCAmelCase_ ,lowerCAmelCase_ ) return k def UpperCamelCase ( __lowercase : dict ,__lowercase : dict ): '''simple docstring''' A_ : int = BigBirdPegasusConfig(**lowerCAmelCase_ ) A_ : List[Any] = BigBirdPegasusForConditionalGeneration(lowerCAmelCase_ ) A_ : Dict = torch_model.state_dict() A_ : Optional[Any] = {} # separating decoder weights A_ : Optional[int] = {k: tf_weights[k] for k in tf_weights if k.startswith('pegasus/decoder' )} A_ : int = {k: tf_weights[k] for k in tf_weights if not k.startswith('pegasus/decoder' )} for k, v in tqdm(decoder_weights.items() ,'tf -> hf conversion' ): A_ : Tuple = [k.endswith(lowerCAmelCase_ ) for ending in KEYS_TO_IGNORE] if any(lowerCAmelCase_ ): continue A_ : int = DECODER_PATTERNS A_ : List[Any] = rename_state_dict_key(lowerCAmelCase_ ,lowerCAmelCase_ ) if new_k not in state_dict: raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): A_ : Tuple = v.T A_ : int = torch.from_numpy(lowerCAmelCase_ ) assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' for k, v in tqdm(remaining_weights.items() ,'tf -> hf conversion' ): A_ : Optional[int] = [k.endswith(lowerCAmelCase_ ) for ending in KEYS_TO_IGNORE] if any(lowerCAmelCase_ ): continue A_ : str = REMAINING_PATTERNS A_ : Dict = rename_state_dict_key(lowerCAmelCase_ ,lowerCAmelCase_ ) if new_k not in state_dict and k != "pegasus/embeddings/position_embeddings": raise ValueError(f'''could not find new key {new_k} in state dict. (converted from {k})''' ) if any(True if i in k else False for i in ['dense', 'query', 'key', 'value'] ): A_ : List[Any] = v.T A_ : int = torch.from_numpy(lowerCAmelCase_ ) if k != "pegasus/embeddings/position_embeddings": assert v.shape == state_dict[new_k].shape, f'''{new_k}, {k}, {v.shape}, {state_dict[new_k].shape}''' A_ : List[str] = mapping['model.embed_positions.weight'] A_ : Any = mapping.pop('model.embed_positions.weight' ) A_ , A_ : Any = torch_model.load_state_dict(lowerCAmelCase_ ,strict=lowerCAmelCase_ ) A_ : int = [ k for k in missing if k not in [ 'final_logits_bias', 'model.encoder.embed_tokens.weight', 'model.decoder.embed_tokens.weight', 'lm_head.weight', ] ] assert unexpected_missing == [], f'''no matches found for the following torch keys {unexpected_missing}''' assert extra == [], f'''no matches found for the following tf keys {extra}''' return torch_model def UpperCamelCase ( __lowercase : Any ): '''simple docstring''' A_ : Union[str, Any] = tf.train.list_variables(lowerCAmelCase_ ) A_ : int = {} A_ : Tuple = ['global_step'] for name, shape in tqdm(lowerCAmelCase_ ,desc='converting tf checkpoint to dict' ): A_ : List[str] = any(pat in name for pat in ignore_name ) if skip_key: continue A_ : List[str] = tf.train.load_variable(lowerCAmelCase_ ,lowerCAmelCase_ ) A_ : int = array return tf_weights def UpperCamelCase ( __lowercase : str ,__lowercase : str ,__lowercase : dict ): '''simple docstring''' A_ : Optional[Any] = get_tf_weights_as_numpy(lowerCAmelCase_ ) A_ : str = convert_bigbird_pegasus(lowerCAmelCase_ ,lowerCAmelCase_ ) torch_model.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() parser.add_argument("""--tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""--save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") _UpperCAmelCase = parser.parse_args() _UpperCAmelCase = {} convert_bigbird_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir, config_update=config_update)
558
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 __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) 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(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) 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" , )
61
0
"""simple docstring""" def __magic_name__ ( _lowerCamelCase: float, _lowerCamelCase: list[float] ) -> str: '''simple docstring''' if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) lowerCAmelCase = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCAmelCase_ ) ) return round(lowerCAmelCase_, ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
535
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __UpperCamelCase : List[Any] = { """configuration_pix2struct""": [ """PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Pix2StructConfig""", """Pix2StructTextConfig""", """Pix2StructVisionConfig""", ], """processing_pix2struct""": ["""Pix2StructProcessor"""], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : List[Any] = ["""Pix2StructImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Optional[int] = [ """PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST""", """Pix2StructPreTrainedModel""", """Pix2StructForConditionalGeneration""", """Pix2StructVisionModel""", """Pix2StructTextModel""", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys __UpperCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
80
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
0
'''simple docstring''' from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class UpperCAmelCase__ : def __init__( self : int,__A : Collection[float] | None = None ): if components is None: _lowerCamelCase : List[Any] = [] _lowerCamelCase : Optional[Any] = list(SCREAMING_SNAKE_CASE__ ) def __len__( self : Tuple ): return len(self.__components ) def __str__( self : List[Any] ): return "(" + ",".join(map(SCREAMING_SNAKE_CASE__,self.__components ) ) + ")" def __add__( self : Tuple,__A : Vector ): _lowerCamelCase : Any = len(self ) if size == len(SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : List[Any] = [self.__components[i] + other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) else: raise Exception("must have the same size" ) def __sub__( self : str,__A : Vector ): _lowerCamelCase : int = len(self ) if size == len(SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : Optional[Any] = [self.__components[i] - other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) else: # error case raise Exception("must have the same size" ) @overload def __mul__( self : List[str],__A : float ): ... @overload def __mul__( self : Dict,__A : Vector ): ... def __mul__( self : int,__A : float | Vector ): if isinstance(SCREAMING_SNAKE_CASE__,(float, int) ): _lowerCamelCase : str = [c * other for c in self.__components] return Vector(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) and len(self ) == len(SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : Tuple = len(self ) _lowerCamelCase : List[Any] = [self.__components[i] * other.component(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ )] return sum(SCREAMING_SNAKE_CASE__ ) else: # error case raise Exception("invalid operand!" ) def lowerCamelCase_ ( self : Optional[int] ): return Vector(self.__components ) def lowerCamelCase_ ( self : Union[str, Any],__A : int ): if isinstance(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception("index out of range" ) def lowerCamelCase_ ( self : str,__A : int,__A : float ): assert -len(self.__components ) <= pos < len(self.__components ) _lowerCamelCase : Optional[int] = value def lowerCamelCase_ ( self : Tuple ): if len(self.__components ) == 0: raise Exception("Vector is empty" ) _lowerCamelCase : Optional[int] = [c**2 for c in self.__components] return math.sqrt(sum(SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase_ ( self : Dict,__A : Vector,__A : bool = False ): _lowerCamelCase : List[str] = self * other _lowerCamelCase : List[Any] = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def A_ ( _lowerCAmelCase : int ): """simple docstring""" assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) return Vector([0] * dimension ) def A_ ( _lowerCAmelCase : int , _lowerCAmelCase : int ): """simple docstring""" assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , lowerCAmelCase_ )) _lowerCamelCase : int = [0] * dimension _lowerCamelCase : List[Any] = 1 return Vector(lowerCAmelCase_ ) def A_ ( _lowerCAmelCase : float , _lowerCAmelCase : Vector , _lowerCAmelCase : Vector ): """simple docstring""" assert ( isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) and (isinstance(lowerCAmelCase_ , (int, float) )) ) return x * scalar + y def A_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int ): """simple docstring""" random.seed(lowerCAmelCase_ ) _lowerCamelCase : Any = [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] return Vector(lowerCAmelCase_ ) class UpperCAmelCase__ : def __init__( self : Tuple,__A : list[list[float]],__A : int,__A : int ): _lowerCamelCase : str = matrix _lowerCamelCase : int = w _lowerCamelCase : Optional[Any] = h def __str__( self : List[str] ): _lowerCamelCase : int = "" for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self : Optional[Any],__A : Matrix ): if self.__width == other.width() and self.__height == other.height(): _lowerCamelCase : str = [] for i in range(self.__height ): _lowerCamelCase : Optional[int] = [ self.__matrix[i][j] + other.component(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] matrix.append(SCREAMING_SNAKE_CASE__ ) return Matrix(SCREAMING_SNAKE_CASE__,self.__width,self.__height ) else: raise Exception("matrix must have the same dimension!" ) def __sub__( self : Optional[int],__A : Matrix ): if self.__width == other.width() and self.__height == other.height(): _lowerCamelCase : str = [] for i in range(self.__height ): _lowerCamelCase : List[str] = [ self.__matrix[i][j] - other.component(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] matrix.append(SCREAMING_SNAKE_CASE__ ) return Matrix(SCREAMING_SNAKE_CASE__,self.__width,self.__height ) else: raise Exception("matrices must have the same dimension!" ) @overload def __mul__( self : Optional[int],__A : float ): ... @overload def __mul__( self : Tuple,__A : Vector ): ... def __mul__( self : List[Any],__A : float | Vector ): if isinstance(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ): # matrix-vector if len(SCREAMING_SNAKE_CASE__ ) == self.__width: _lowerCamelCase : Dict = zero_vector(self.__height ) for i in range(self.__height ): _lowerCamelCase : List[str] = [ self.__matrix[i][j] * other.component(SCREAMING_SNAKE_CASE__ ) for j in range(self.__width ) ] ans.change_component(SCREAMING_SNAKE_CASE__,sum(SCREAMING_SNAKE_CASE__ ) ) return ans else: raise Exception( "vector must have the same size as the " "number of columns of the matrix!" ) elif isinstance(SCREAMING_SNAKE_CASE__,(int, float) ): # matrix-scalar _lowerCamelCase : Any = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(SCREAMING_SNAKE_CASE__,self.__width,self.__height ) return None def lowerCamelCase_ ( self : Dict ): return self.__height def lowerCamelCase_ ( self : Dict ): return self.__width def lowerCamelCase_ ( self : int,__A : int,__A : int ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception("change_component: indices out of bounds" ) def lowerCamelCase_ ( self : Optional[int],__A : int,__A : int,__A : float ): if 0 <= x < self.__height and 0 <= y < self.__width: _lowerCamelCase : Optional[Any] = value else: raise Exception("change_component: indices out of bounds" ) def lowerCamelCase_ ( self : Union[str, Any],__A : int,__A : int ): if self.__height != self.__width: raise Exception("Matrix is not square" ) _lowerCamelCase : List[str] = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): _lowerCamelCase : str = minor[i][:y] + minor[i][y + 1 :] return Matrix(SCREAMING_SNAKE_CASE__,self.__width - 1,self.__height - 1 ).determinant() def lowerCamelCase_ ( self : List[Any],__A : int,__A : int ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) else: raise Exception("Indices out of bounds" ) def lowerCamelCase_ ( self : Any ): if self.__height != self.__width: raise Exception("Matrix is not square" ) if self.__height < 1: raise Exception("Matrix has no element" ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: _lowerCamelCase : int = [ self.__matrix[0][y] * self.cofactor(0,SCREAMING_SNAKE_CASE__ ) for y in range(self.__width ) ] return sum(SCREAMING_SNAKE_CASE__ ) def A_ ( _lowerCAmelCase : int ): """simple docstring""" _lowerCamelCase : int = [[0] * n for _ in range(lowerCAmelCase_ )] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) def A_ ( _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int , _lowerCAmelCase : int ): """simple docstring""" random.seed(lowerCAmelCase_ ) _lowerCamelCase : Tuple = [ [random.randint(lowerCAmelCase_ , lowerCAmelCase_ ) for _ in range(lowerCAmelCase_ )] for _ in range(lowerCAmelCase_ ) ] return Matrix(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
44
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
0
import math import sys def snake_case__ ( SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : Union[str, Any] = '' try: with open(lowerCAmelCase_ , 'rb' ) as binary_file: lowercase__ : str = binary_file.read() for dat in data: lowercase__ : List[Any] = f"""{dat:08b}""" result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def snake_case__ ( SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : Optional[Any] = {'0': '0', '1': '1'} lowercase__ , lowercase__ : Optional[int] = '', '' lowercase__ : Any = len(lowerCAmelCase_ ) for i in range(len(lowerCAmelCase_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue lowercase__ : Optional[int] = lexicon[curr_string] result += last_match_id lowercase__ : Union[str, Any] = last_match_id + '0' if math.loga(lowerCAmelCase_ ).is_integer(): lowercase__ : List[str] = {} for curr_key in list(lowerCAmelCase_ ): lowercase__ : int = lexicon.pop(lowerCAmelCase_ ) lowercase__ : str = new_lex lowercase__ : str = last_match_id + '1' index += 1 lowercase__ : Any = '' return result def snake_case__ ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : Optional[int] = 8 try: with open(lowerCAmelCase_ , 'wb' ) as opened_file: lowercase__ : int = [ to_write[i : i + byte_length] for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('10000000' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowerCAmelCase_ , 2 ).to_bytes(1 , byteorder='big' ) ) except OSError: print('File not accessible' ) sys.exit() def snake_case__ ( SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : List[Any] = 0 for letter in data_bits: if letter == "1": break counter += 1 lowercase__ : Tuple = data_bits[counter:] lowercase__ : Optional[int] = data_bits[counter + 1 :] return data_bits def snake_case__ ( SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' lowercase__ : Any = read_file_binary(lowerCAmelCase_ ) lowercase__ : Optional[Any] = remove_prefix(lowerCAmelCase_ ) lowercase__ : Optional[Any] = decompress_data(lowerCAmelCase_ ) write_file_binary(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
164
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
0
"""simple docstring""" from __future__ import annotations def lowercase (snake_case__ : int ) -> List[str]: '''simple docstring''' lowerCAmelCase = 2 lowerCAmelCase = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(lowerCAmelCase_ ) if n > 1: factors.append(lowerCAmelCase_ ) return factors if __name__ == "__main__": import doctest doctest.testmod()
169
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
0
class A__ : def __init__( self , __magic_name__ ): lowerCamelCase : List[Any] = size lowerCamelCase : Dict = [0] * size lowerCamelCase : Optional[int] = [0] * size @staticmethod def UpperCamelCase__ ( __magic_name__ ): return index | (index + 1) @staticmethod def UpperCamelCase__ ( __magic_name__ ): return (index & (index + 1)) - 1 def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): lowerCamelCase : str = value while index < self.size: lowerCamelCase : Optional[int] = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCamelCase : Union[str, Any] = value else: lowerCamelCase : Union[str, Any] = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Tuple = self.get_next(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): right -= 1 # Because of right is exclusive lowerCamelCase : Optional[Any] = 0 while left <= right: lowerCamelCase : Optional[Any] = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCamelCase : Union[str, Any] = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCamelCase : int = current_left else: lowerCamelCase : Tuple = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
681
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
0
'''simple docstring''' def __UpperCAmelCase ( __magic_name__ ,__magic_name__ )-> str: """simple docstring""" return "\n".join( F'''{number} * {i} = {number * i}''' for i in range(1 ,number_of_terms + 1 ) ) if __name__ == "__main__": print(multiplication_table(number=5, number_of_terms=10))
653
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCAmelCase_ ( UpperCamelCase__ ,unittest.TestCase ): __lowerCamelCase : str = VideoToVideoSDPipeline __lowerCamelCase : Dict = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} __lowerCamelCase : Tuple = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} __lowerCamelCase : Dict = PipelineTesterMixin.required_optional_params - {"latents"} __lowerCamelCase : Tuple = False # No `output_type`. __lowerCamelCase : Optional[Any] = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def _snake_case ( self ) -> Optional[int]: torch.manual_seed(0 ) _lowerCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) _lowerCAmelCase = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) _lowerCAmelCase = 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 , sample_size=128 , ) torch.manual_seed(0 ) _lowerCAmelCase = 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 , hidden_act="gelu" , projection_dim=512 , ) _lowerCAmelCase = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) _lowerCAmelCase = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase=0 ) -> Tuple: # 3 frames _lowerCAmelCase = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): _lowerCAmelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: _lowerCAmelCase = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def _snake_case ( self ) -> str: _lowerCAmelCase = "cpu" # ensure determinism for the device-dependent torch.Generator _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = "np" _lowerCAmelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames _lowerCAmelCase = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) _lowerCAmelCase = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _snake_case ( self ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5E-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _snake_case ( self ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _snake_case ( self ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def _snake_case ( self ) -> Optional[int]: pass def _snake_case ( self ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class lowerCAmelCase_ ( unittest.TestCase ): def _snake_case ( self ) -> int: _lowerCAmelCase = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames _lowerCAmelCase = torch.Generator(device="cpu" ).manual_seed(0 ) _lowerCAmelCase = torch.randn((1, 10, 3, 1024, 576) , generator=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = video.to("cuda" ) _lowerCAmelCase = "Spiderman is surfing" _lowerCAmelCase = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames _lowerCAmelCase = np.array([-1.0458984, -1.1279297, -0.9663086, -0.91503906, -0.75097656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
18
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
"""simple docstring""" def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = 0 ) ->str: _lowerCamelCase : int = length or len(lowerCAmelCase_ ) _lowerCamelCase : Optional[Any] = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: _lowerCamelCase, _lowerCamelCase : Dict = list_data[i + 1], list_data[i] _lowerCamelCase : List[Any] = True return list_data if not swapped else bubble_sort(lowerCAmelCase_ , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
434
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def __lowerCamelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCamelCase ( self : List[str] ) -> int: """simple docstring""" _lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) _lowerCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('sample_euler' ) _lowerCAmelCase = 'A painting of a squirrel eating a burger' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) _lowerCAmelCase = output.images _lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCAmelCase = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" _lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) _lowerCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('sample_euler' ) _lowerCAmelCase = 'A painting of a squirrel eating a burger' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = sd_pipe([prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) _lowerCAmelCase = output.images _lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCAmelCase = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def __lowerCamelCase ( self : Dict ) -> str: """simple docstring""" _lowerCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) _lowerCAmelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) sd_pipe.set_scheduler('sample_dpmpp_2m' ) _lowerCAmelCase = 'A painting of a squirrel eating a burger' _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = sd_pipe( [prompt] , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=15 , output_type='np' , use_karras_sigmas=SCREAMING_SNAKE_CASE__ , ) _lowerCAmelCase = output.images _lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCAmelCase = np.array( [0.11381689, 0.12112921, 0.1389457, 0.12549606, 0.1244964, 0.10831517, 0.11562866, 0.10867816, 0.10499048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
580
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class UpperCAmelCase ( UpperCamelCase__ ): '''simple docstring''' lowerCamelCase_ = (DPMSolverSDEScheduler,) lowerCamelCase_ = 1_0 def lowerCAmelCase_ ( self , **lowercase ): """simple docstring""" A_ : List[Any] = { 'num_train_timesteps': 1_1_0_0, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def lowerCAmelCase_ ( self ): """simple docstring""" for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self ): """simple docstring""" for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__ , beta_end=SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self ): """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : List[str] = self.scheduler_classes[0] A_ : Optional[int] = self.get_scheduler_config() A_ : str = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) A_ : List[Any] = self.dummy_model() A_ : Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma A_ : Optional[int] = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): A_ : List[str] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : str = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Dict = output.prev_sample A_ : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A_ : Any = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1E-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1E-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1E-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1E-3 def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Optional[int] = self.scheduler_classes[0] A_ : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction' ) A_ : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) A_ : List[str] = self.dummy_model() A_ : List[str] = self.dummy_sample_deter * scheduler.init_noise_sigma A_ : Tuple = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): A_ : Optional[int] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : str = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Any = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Tuple = output.prev_sample A_ : Optional[int] = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A_ : int = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1E-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1E-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1E-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1E-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1E-3 def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Union[str, Any] = self.scheduler_classes[0] A_ : Optional[int] = self.get_scheduler_config() A_ : str = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) A_ : str = self.dummy_model() A_ : Dict = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: A_ : int = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : List[Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Dict = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Dict = output.prev_sample A_ : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A_ : Optional[int] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1E-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1E-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1E-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1E-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1E-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1E-3 def lowerCAmelCase_ ( self ): """simple docstring""" A_ : str = self.scheduler_classes[0] A_ : Tuple = self.get_scheduler_config() A_ : Optional[int] = scheduler_class(**SCREAMING_SNAKE_CASE__ , use_karras_sigmas=SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps , device=SCREAMING_SNAKE_CASE__ ) A_ : List[str] = self.dummy_model() A_ : Dict = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma A_ : str = sample.to(SCREAMING_SNAKE_CASE__ ) for t in scheduler.timesteps: A_ : List[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Union[str, Any] = model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : List[str] = scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A_ : Optional[Any] = output.prev_sample A_ : str = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A_ : Dict = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1E-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1E-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1E-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1E-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1E-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1E-2
558
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
"""simple docstring""" 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 lowercase ( unittest.TestCase ): def UpperCAmelCase (self : Any ) -> int: """simple docstring""" lowerCAmelCase = '''ZinengTang/tvlt-base''' lowerCAmelCase = tempfile.mkdtemp() def UpperCAmelCase (self : List[Any] ,**SCREAMING_SNAKE_CASE_ : Optional[Any] ) -> List[Any]: """simple docstring""" return TvltImageProcessor.from_pretrained(self.checkpoint ,**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase (self : int ,**SCREAMING_SNAKE_CASE_ : List[Any] ) -> str: """simple docstring""" return TvltFeatureExtractor.from_pretrained(self.checkpoint ,**SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase (self : List[str] ) -> Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase (self : Any ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_feature_extractor() lowerCAmelCase = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor ,SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor ,SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase (self : Tuple ) -> List[Any]: """simple docstring""" lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_feature_extractor() lowerCAmelCase = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = np.ones([12_000] ) lowerCAmelCase = feature_extractor(SCREAMING_SNAKE_CASE__ ,return_tensors='''np''' ) lowerCAmelCase = processor(audio=SCREAMING_SNAKE_CASE__ ,return_tensors='''np''' ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def UpperCAmelCase (self : Dict ) -> str: """simple docstring""" lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_feature_extractor() lowerCAmelCase = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = np.ones([3, 224, 224] ) lowerCAmelCase = image_processor(SCREAMING_SNAKE_CASE__ ,return_tensors='''np''' ) lowerCAmelCase = processor(images=SCREAMING_SNAKE_CASE__ ,return_tensors='''np''' ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() ,input_processor[key].sum() ,delta=1e-2 ) def UpperCAmelCase (self : int ) -> Any: """simple docstring""" lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_feature_extractor() lowerCAmelCase = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase = np.ones([12_000] ) lowerCAmelCase = np.ones([3, 224, 224] ) lowerCAmelCase = processor(audio=SCREAMING_SNAKE_CASE__ ,images=SCREAMING_SNAKE_CASE__ ) 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(SCREAMING_SNAKE_CASE__ ): processor() def UpperCAmelCase (self : Tuple ) -> Optional[Any]: """simple docstring""" lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_feature_extractor() lowerCAmelCase = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ ,feature_extractor=SCREAMING_SNAKE_CASE__ ) 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''' ,)
535
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
from typing import Dict from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, get_torch_dist_unique_port, require_torch_multi_gpu, require_torch_neuroncore, ) from transformers.training_args import ParallelMode from transformers.utils import logging __UpperCamelCase : str = logging.get_logger(__name__) if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset from transformers import Trainer class __UpperCamelCase ( UpperCamelCase__ ): def __init__( self : List[Any] , _lowerCAmelCase : int = 101 ) -> List[str]: """simple docstring""" __lowercase = length def __len__( self : Tuple ) -> Union[str, Any]: """simple docstring""" return self.length def __getitem__( self : Dict , _lowerCAmelCase : str ) -> int: """simple docstring""" return i class __UpperCamelCase : def __call__( self : int , _lowerCAmelCase : List[str] ) -> int: """simple docstring""" return {"input_ids": torch.tensor(SCREAMING_SNAKE_CASE__ ), "labels": torch.tensor(SCREAMING_SNAKE_CASE__ )} class __UpperCamelCase ( nn.Module ): def __init__( self : Optional[int] ) -> Any: """simple docstring""" super().__init__() # Add some (unused) params otherwise DDP will complain. __lowercase = nn.Linear(120 , 80 ) def _a ( self : Any , _lowerCAmelCase : int , _lowerCAmelCase : List[str]=None ) -> Optional[Any]: """simple docstring""" if labels is not None: return torch.tensor(0.0 , device=input_ids.device ), input_ids else: return input_ids class __UpperCamelCase ( UpperCamelCase__ ): @require_torch_neuroncore def _a ( self : Tuple ) -> Optional[Any]: """simple docstring""" __lowercase = F'--nproc_per_node=2\n --master_port={get_torch_dist_unique_port()}\n {self.test_file_dir}/test_trainer_distributed.py\n '.split() __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F'--output_dir {output_dir}'.split() __lowercase = ["""torchrun"""] + distributed_args + args execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call class __UpperCamelCase ( UpperCamelCase__ ): @require_torch_multi_gpu def _a ( self : Dict ) -> List[str]: """simple docstring""" __lowercase = F'--nproc_per_node={torch.cuda.device_count()}\n --master_port={get_torch_dist_unique_port()}\n {self.test_file_dir}/test_trainer_distributed.py\n '.split() __lowercase = self.get_auto_remove_tmp_dir() __lowercase = F'--output_dir {output_dir}'.split() __lowercase = ["""torchrun"""] + distributed_args + args execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) # successful return here == success - any errors would have caused an error in the sub-call if __name__ == "__main__": # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: # # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py __UpperCamelCase : List[Any] = HfArgumentParser((TrainingArguments,)) __UpperCamelCase : Dict = parser.parse_args_into_dataclasses()[0] logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, ''' F'''distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}''' ) # Essentially, what we want to verify in the distributed case is that we get all samples back, # in the right order. (this is crucial for prediction for instance) for dataset_length in [101, 40, 7]: __UpperCamelCase : Any = DummyDataset(dataset_length) def snake_case ( lowerCamelCase ): '''simple docstring''' __lowercase = list(range(len(lowerCAmelCase_ ) ) ) __lowercase = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential if not success and training_args.local_rank == 0: logger.warning( """Predictions and/or labels do not match expected results:\n - predictions: """ F'{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}' ) return {"success": success} __UpperCamelCase : List[Any] = Trainer( model=DummyModel(), args=training_args, data_collator=DummyDataCollator(), eval_dataset=dataset, compute_metrics=compute_metrics, ) __UpperCamelCase : Union[str, Any] = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __UpperCamelCase : Union[str, Any] = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __UpperCamelCase : Tuple = 2 __UpperCamelCase : Any = trainer.evaluate() logger.info(metrics) if metrics["eval_success"] is not True: logger.error(metrics) exit(1) __UpperCamelCase : Union[str, Any] = trainer.predict(dataset) logger.info(p.metrics) if p.metrics["test_success"] is not True: logger.error(p.metrics) exit(1) __UpperCamelCase : Optional[Any] = None
80
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = 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 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class UpperCAmelCase__ ( UpperCamelCase__ ): lowerCAmelCase_ = (KDPMaDiscreteScheduler,) lowerCAmelCase_ = 10 def lowerCamelCase_ ( self : Dict,**__A : int ): _lowerCamelCase : Tuple = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**SCREAMING_SNAKE_CASE__ ) return config def lowerCamelCase_ ( self : Optional[Any] ): for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : str ): for beta_start, beta_end in zip([0.00001, 0.0001, 0.001],[0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=SCREAMING_SNAKE_CASE__,beta_end=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : Dict ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : Optional[int] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : Dict = self.scheduler_classes[0] _lowerCamelCase : str = self.get_scheduler_config(prediction_type="v_prediction" ) _lowerCamelCase : str = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) _lowerCamelCase : List[Any] = self.dummy_model() _lowerCamelCase : Dict = self.dummy_sample_deter * scheduler.init_noise_sigma _lowerCamelCase : Dict = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): _lowerCamelCase : Union[str, Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Any = model(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[Any] = output.prev_sample _lowerCamelCase : int = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) _lowerCamelCase : str = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.69_34e-07 ) < 1e-2 assert abs(result_mean.item() - 6.11_12e-10 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72e-07 ) < 1e-2 assert abs(result_mean.item() - 0.0002 ) < 1e-3 def lowerCamelCase_ ( self : Dict ): if torch_device == "mps": return _lowerCamelCase : List[str] = self.scheduler_classes[0] _lowerCamelCase : int = self.get_scheduler_config() _lowerCamelCase : Any = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps ) _lowerCamelCase : int = self.dummy_model() _lowerCamelCase : str = self.dummy_sample_deter * scheduler.init_noise_sigma _lowerCamelCase : str = sample.to(SCREAMING_SNAKE_CASE__ ) for i, t in enumerate(scheduler.timesteps ): _lowerCamelCase : Union[str, Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[Any] = output.prev_sample _lowerCamelCase : Dict = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) _lowerCamelCase : List[str] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 def lowerCamelCase_ ( self : Optional[int] ): if torch_device == "mps": return _lowerCamelCase : List[Any] = self.scheduler_classes[0] _lowerCamelCase : List[Any] = self.get_scheduler_config() _lowerCamelCase : List[str] = scheduler_class(**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(self.num_inference_steps,device=SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[Any] = self.dummy_model() _lowerCamelCase : List[Any] = self.dummy_sample_deter.to(SCREAMING_SNAKE_CASE__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _lowerCamelCase : Optional[Any] = scheduler.scale_model_input(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Tuple = model(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Any = scheduler.step(SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = output.prev_sample _lowerCamelCase : int = torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) _lowerCamelCase : List[Any] = torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) if str(SCREAMING_SNAKE_CASE__ ).startswith("cpu" ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3 else: # CUDA assert abs(result_sum.item() - 20.4125 ) < 1e-2 assert abs(result_mean.item() - 0.0266 ) < 1e-3
44
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
from __future__ import annotations class SCREAMING_SNAKE_CASE__ : def __init__( self , a=None): lowercase__ : Any = data lowercase__ : Optional[int] = None def __repr__( self): lowercase__ : Optional[int] = [] lowercase__ : Any = self while temp: string_rep.append(f"""{temp.data}""") lowercase__ : Optional[int] = temp.next return "->".join(SCREAMING_SNAKE_CASE__) def snake_case__ ( SCREAMING_SNAKE_CASE_ : list ): '''simple docstring''' if not elements_list: raise Exception('The Elements List is empty' ) lowercase__ : Dict = Node(elements_list[0] ) for i in range(1 , len(lowerCAmelCase_ ) ): lowercase__ : List[str] = Node(elements_list[i] ) lowercase__ : Optional[Any] = current.next return head def snake_case__ ( SCREAMING_SNAKE_CASE_ : Node ): '''simple docstring''' if head_node is not None and isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): print_reverse(head_node.next ) print(head_node.data ) def snake_case__ ( ): '''simple docstring''' from doctest import testmod testmod() lowercase__ : Any = make_linked_list([14, 52, 14, 12, 43] ) print('Linked List:' ) print(lowerCAmelCase_ ) print('Elements in Reverse:' ) print_reverse(lowerCAmelCase_ ) if __name__ == "__main__": main()
164
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
"""simple docstring""" class SCREAMING_SNAKE_CASE__ : def __init__( self : List[str] , lowerCAmelCase : str ): lowerCAmelCase = val lowerCAmelCase = None lowerCAmelCase = None def __lowercase ( self : Optional[Any] , lowerCAmelCase : List[str] ): if self.val: if val < self.val: if self.left is None: lowerCAmelCase = Node(SCREAMING_SNAKE_CASE__ ) else: self.left.insert(SCREAMING_SNAKE_CASE__ ) elif val > self.val: if self.right is None: lowerCAmelCase = Node(SCREAMING_SNAKE_CASE__ ) else: self.right.insert(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase = val def lowercase (snake_case__ : Optional[Any] , snake_case__ : str ) -> List[str]: '''simple docstring''' if root: inorder(root.left , lowerCAmelCase_ ) res.append(root.val ) inorder(root.right , lowerCAmelCase_ ) def lowercase (snake_case__ : Dict ) -> Dict: '''simple docstring''' if len(lowerCAmelCase_ ) == 0: return arr lowerCAmelCase = Node(arr[0] ) for i in range(1 , len(lowerCAmelCase_ ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCAmelCase = [] inorder(lowerCAmelCase_ , lowerCAmelCase_ ) return res if __name__ == "__main__": print(tree_sort([1_0, 1, 3, 2, 9, 1_4, 1_3]))
169
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0
import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A__ ( UpperCamelCase__): _UpperCAmelCase : Optional[int] = ["""image_processor""", """tokenizer"""] _UpperCAmelCase : str = """LayoutLMv2ImageProcessor""" _UpperCAmelCase : List[str] = ("""LayoutXLMTokenizer""", """LayoutXLMTokenizerFast""") def __init__( self , __magic_name__=None , __magic_name__=None , **__magic_name__ ): if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , SCREAMING_SNAKE_CASE__ , ) lowerCamelCase : int = kwargs.pop("""feature_extractor""" ) lowerCamelCase : 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`.""" ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __call__( self , __magic_name__ , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = True , __magic_name__ = False , __magic_name__ = None , __magic_name__ = None , __magic_name__ = 0 , __magic_name__ = None , __magic_name__ = None , __magic_name__ = None , __magic_name__ = False , __magic_name__ = False , __magic_name__ = False , __magic_name__ = False , __magic_name__ = True , __magic_name__ = None , **__magic_name__ , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( """You cannot provide bounding boxes """ """if you initialized the image processor with apply_ocr set to True.""" ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( """You cannot provide word labels if you initialized the image processor with apply_ocr set to True.""" ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping.""" ) # first, apply the image processor lowerCamelCase : str = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowerCamelCase : Optional[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) lowerCamelCase : Any = features["""words"""] lowerCamelCase : str = self.tokenizer( text=text if text is not None else features["""words"""] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["""boxes"""] , word_labels=SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , stride=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_overflowing_tokens=SCREAMING_SNAKE_CASE__ , return_special_tokens_mask=SCREAMING_SNAKE_CASE__ , return_offsets_mapping=SCREAMING_SNAKE_CASE__ , return_length=SCREAMING_SNAKE_CASE__ , verbose=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # add pixel values lowerCamelCase : Dict = features.pop("""pixel_values""" ) if return_overflowing_tokens is True: lowerCamelCase : Any = self.get_overflowing_images(SCREAMING_SNAKE_CASE__ , encoded_inputs["""overflow_to_sample_mapping"""] ) lowerCamelCase : Optional[int] = images return encoded_inputs def UpperCamelCase__ ( self , __magic_name__ , __magic_name__ ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image lowerCamelCase : List[Any] = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got""" F''' {len(SCREAMING_SNAKE_CASE__ )} and {len(SCREAMING_SNAKE_CASE__ )}''' ) return images_with_overflow def UpperCamelCase__ ( self , *__magic_name__ , **__magic_name__ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( self , *__magic_name__ , **__magic_name__ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @property def UpperCamelCase__ ( self ): return ["input_ids", "bbox", "attention_mask", "image"] @property def UpperCamelCase__ ( self ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def UpperCamelCase__ ( self ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
681
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
0
'''simple docstring''' from __future__ import annotations __lowerCamelCase : List[str] = '''#''' class A_ : """simple docstring""" def __init__( self :Dict ) -> None: '''simple docstring''' snake_case_ : List[Any] = {} def _A ( self :Any , lowerCAmelCase__ :str ) -> None: '''simple docstring''' snake_case_ : Optional[int] = self._trie for char in text: if char not in trie: snake_case_ : int = {} snake_case_ : List[Any] = trie[char] snake_case_ : List[str] = True def _A ( self :List[str] , lowerCAmelCase__ :str ) -> tuple | list: '''simple docstring''' snake_case_ : Optional[int] = self._trie for char in prefix: if char in trie: snake_case_ : Any = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def _A ( self :Optional[int] , lowerCAmelCase__ :dict ) -> tuple: '''simple docstring''' snake_case_ : Tuple = [] for c, v in d.items(): snake_case_ : Optional[Any] = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = Trie() __lowerCamelCase : List[Any] = ('''depart''', '''detergent''', '''daring''', '''dog''', '''deer''', '''deal''') for word in words: trie.insert_word(word) def __UpperCAmelCase ( __magic_name__ )-> Optional[int]: """simple docstring""" snake_case_ : int = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def __UpperCAmelCase ( )-> Dict: """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
653
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
0
'''simple docstring''' import functools def __a(SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' _lowerCAmelCase = len(lowerCAmelCase_ ) _lowerCAmelCase = len(lowerCAmelCase_ ) @functools.cache def min_distance(SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa _lowerCAmelCase = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , lowerCAmelCase_ ) , 1 + min_distance(lowerCAmelCase_ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
18
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
0
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def UpperCamelCase ( ) ->Dict: raise RuntimeError('''CUDA out of memory.''' ) class _UpperCAmelCase ( nn.Module ): """simple docstring""" def __init__( self ) -> str: super().__init__() _lowerCamelCase : Optional[int] = nn.Linear(3 , 4 ) _lowerCamelCase : Dict = nn.BatchNormad(4 ) _lowerCamelCase : str = nn.Linear(4 , 5 ) def a__ ( self , _lowercase ) -> int: return self.lineara(self.batchnorm(self.lineara(SCREAMING_SNAKE_CASE__ ) ) ) class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def a__ ( self ) -> Tuple: _lowerCamelCase : Tuple = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(_lowercase ): nonlocal batch_sizes batch_sizes.append(SCREAMING_SNAKE_CASE__ ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(SCREAMING_SNAKE_CASE__ , [128, 64, 32, 16, 8] ) def a__ ( self ) -> Optional[int]: _lowerCamelCase : int = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(_lowercase , _lowercase ): nonlocal batch_sizes batch_sizes.append(SCREAMING_SNAKE_CASE__ ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga _lowerCamelCase, _lowerCamelCase : str = mock_training_loop_function('''hello''' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, '''hello'''] ) def a__ ( self ) -> Any: @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(_lowercase ): pass with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def a__ ( self ) -> Any: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(_lowercase ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0] ) def a__ ( self ) -> Union[str, Any]: @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(_lowercase , _lowercase , _lowercase ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function(128 , '''hello''' , '''world''' ) self.assertIn('''Batch size was passed into `f`''' , cm.exception.args[0] ) self.assertIn('''`f(arg1=\'hello\', arg2=\'world\')''' , cm.exception.args[0] ) def a__ ( self ) -> List[Any]: @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(_lowercase ): raise ValueError('''Oops, we had an error!''' ) with self.assertRaises(SCREAMING_SNAKE_CASE__ ) as cm: mock_training_loop_function() self.assertIn('''Oops, we had an error!''' , cm.exception.args[0] ) @require_cuda def a__ ( self ) -> List[str]: _lowerCamelCase : Dict = torch.cuda.memory_allocated() _lowerCamelCase : Tuple = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Dict = release_memory(SCREAMING_SNAKE_CASE__ ) self.assertEqual(torch.cuda.memory_allocated() , SCREAMING_SNAKE_CASE__ )
434
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { '''configuration_resnet''': ['''RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ResNetConfig''', '''ResNetOnnxConfig'''] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ '''RESNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ResNetForImageClassification''', '''ResNetModel''', '''ResNetPreTrainedModel''', '''ResNetBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ '''TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFResNetForImageClassification''', '''TFResNetModel''', '''TFResNetPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = [ '''FlaxResNetForImageClassification''', '''FlaxResNetModel''', '''FlaxResNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys _snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
580
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
0
import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , lowercase , lowercase=7 , lowercase=3 , lowercase=1_8 , lowercase=3_0 , lowercase=4_0_0 , lowercase=True , lowercase=None , lowercase=True , ): """simple docstring""" A_ : List[str] = size if size is not None else {'height': 1_8, 'width': 1_8} A_ : str = parent A_ : Any = batch_size A_ : Union[str, Any] = num_channels A_ : int = image_size A_ : str = min_resolution A_ : List[Any] = max_resolution A_ : Tuple = do_resize A_ : Union[str, Any] = size A_ : List[Any] = apply_ocr def lowerCAmelCase_ ( self ): """simple docstring""" return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCAmelCase ( UpperCamelCase__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ = LayoutLMvaImageProcessor if is_pytesseract_available() else None def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Tuple = LayoutLMvaImageProcessingTester(self ) @property def lowerCAmelCase_ ( self ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'apply_ocr' ) ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 1_8, 'width': 1_8} ) A_ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'height': 4_2, 'width': 4_2} ) def lowerCAmelCase_ ( self ): """simple docstring""" pass def lowerCAmelCase_ ( self ): """simple docstring""" A_ : int = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A_ : Any = image_processing(image_inputs[0] , return_tensors='pt' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) self.assertIsInstance(encoding.words , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # Test batched A_ : Dict = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A_ : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A_ : Dict = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched A_ : int = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A_ : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A_ : Optional[Any] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) # Test batched A_ : Optional[Any] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['height'], self.image_processor_tester.size['width'], ) , ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ : Any = LayoutLMvaImageProcessor() from datasets import load_dataset A_ : Optional[Any] = load_dataset('hf-internal-testing/fixtures_docvqa' , split='test' ) A_ : Dict = Image.open(ds[0]['file'] ).convert('RGB' ) A_ : Dict = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 A_ : Tuple = [['11:14', 'to', '11:39', 'a.m', '11:39', 'to', '11:44', 'a.m.', '11:44', 'a.m.', 'to', '12:25', 'p.m.', '12:25', 'to', '12:58', 'p.m.', '12:58', 'to', '4:00', 'p.m.', '2:00', 'to', '5:00', 'p.m.', 'Coffee', 'Break', 'Coffee', 'will', 'be', 'served', 'for', 'men', 'and', 'women', 'in', 'the', 'lobby', 'adjacent', 'to', 'exhibit', 'area.', 'Please', 'move', 'into', 'exhibit', 'area.', '(Exhibits', 'Open)', 'TRRF', 'GENERAL', 'SESSION', '(PART', '|)', 'Presiding:', 'Lee', 'A.', 'Waller', 'TRRF', 'Vice', 'President', '“Introductory', 'Remarks”', 'Lee', 'A.', 'Waller,', 'TRRF', 'Vice', 'Presi-', 'dent', 'Individual', 'Interviews', 'with', 'TRRF', 'Public', 'Board', 'Members', 'and', 'Sci-', 'entific', 'Advisory', 'Council', 'Mem-', 'bers', 'Conducted', 'by', 'TRRF', 'Treasurer', 'Philip', 'G.', 'Kuehn', 'to', 'get', 'answers', 'which', 'the', 'public', 'refrigerated', 'warehousing', 'industry', 'is', 'looking', 'for.', 'Plus', 'questions', 'from', 'the', 'floor.', 'Dr.', 'Emil', 'M.', 'Mrak,', 'University', 'of', 'Cal-', 'ifornia,', 'Chairman,', 'TRRF', 'Board;', 'Sam', 'R.', 'Cecil,', 'University', 'of', 'Georgia', 'College', 'of', 'Agriculture;', 'Dr.', 'Stanley', 'Charm,', 'Tufts', 'University', 'School', 'of', 'Medicine;', 'Dr.', 'Robert', 'H.', 'Cotton,', 'ITT', 'Continental', 'Baking', 'Company;', 'Dr.', 'Owen', 'Fennema,', 'University', 'of', 'Wis-', 'consin;', 'Dr.', 'Robert', 'E.', 'Hardenburg,', 'USDA.', 'Questions', 'and', 'Answers', 'Exhibits', 'Open', 'Capt.', 'Jack', 'Stoney', 'Room', 'TRRF', 'Scientific', 'Advisory', 'Council', 'Meeting', 'Ballroom', 'Foyer']] # noqa: E231 A_ : str = [[[1_4_1, 5_7, 2_1_4, 6_9], [2_2_8, 5_8, 2_5_2, 6_9], [1_4_1, 7_5, 2_1_6, 8_8], [2_3_0, 7_9, 2_8_0, 8_8], [1_4_2, 2_6_0, 2_1_8, 2_7_3], [2_3_0, 2_6_1, 2_5_5, 2_7_3], [1_4_3, 2_7_9, 2_1_8, 2_9_0], [2_3_1, 2_8_2, 2_9_0, 2_9_1], [1_4_3, 3_4_2, 2_1_8, 3_5_4], [2_3_1, 3_4_5, 2_8_9, 3_5_5], [2_0_2, 3_6_2, 2_2_7, 3_7_3], [1_4_3, 3_7_9, 2_2_0, 3_9_2], [2_3_1, 3_8_2, 2_9_1, 3_9_4], [1_4_4, 7_1_4, 2_2_0, 7_2_6], [2_3_1, 7_1_5, 2_5_6, 7_2_6], [1_4_4, 7_3_2, 2_2_0, 7_4_5], [2_3_2, 7_3_6, 2_9_1, 7_4_7], [1_4_4, 7_6_9, 2_1_8, 7_8_2], [2_3_1, 7_7_0, 2_5_6, 7_8_2], [1_4_1, 7_8_8, 2_0_2, 8_0_1], [2_1_5, 7_9_1, 2_7_4, 8_0_4], [1_4_3, 8_2_6, 2_0_4, 8_3_8], [2_1_5, 8_2_6, 2_4_0, 8_3_8], [1_4_2, 8_4_4, 2_0_2, 8_5_7], [2_1_5, 8_4_7, 2_7_4, 8_5_9], [3_3_4, 5_7, 4_2_7, 6_9], [4_4_0, 5_7, 5_2_2, 6_9], [3_6_9, 7_5, 4_6_1, 8_8], [4_6_9, 7_5, 5_1_6, 8_8], [5_2_8, 7_6, 5_6_2, 8_8], [5_7_0, 7_6, 6_6_7, 8_8], [6_7_5, 7_5, 7_1_1, 8_7], [7_2_1, 7_9, 7_7_8, 8_8], [7_8_9, 7_5, 8_4_0, 8_8], [3_6_9, 9_7, 4_7_0, 1_0_7], [4_8_4, 9_4, 5_0_7, 1_0_6], [5_1_8, 9_4, 5_6_2, 1_0_7], [5_7_6, 9_4, 6_5_5, 1_1_0], [6_6_8, 9_4, 7_9_2, 1_0_9], [8_0_4, 9_5, 8_2_9, 1_0_7], [3_6_9, 1_1_3, 4_6_5, 1_2_5], [4_7_7, 1_1_6, 5_4_7, 1_2_5], [5_6_2, 1_1_3, 6_5_8, 1_2_5], [6_7_1, 1_1_6, 7_4_8, 1_2_5], [7_6_1, 1_1_3, 8_1_1, 1_2_5], [3_6_9, 1_3_1, 4_6_5, 1_4_3], [4_7_7, 1_3_3, 5_4_8, 1_4_3], [5_6_3, 1_3_0, 6_9_8, 1_4_5], [7_1_0, 1_3_0, 8_0_2, 1_4_6], [3_3_6, 1_7_1, 4_1_2, 1_8_3], [4_2_3, 1_7_1, 5_7_2, 1_8_3], [5_8_2, 1_7_0, 7_1_6, 1_8_4], [7_2_8, 1_7_1, 8_1_7, 1_8_7], [8_2_9, 1_7_1, 8_4_4, 1_8_6], [3_3_8, 1_9_7, 4_8_2, 2_1_2], [5_0_7, 1_9_6, 5_5_7, 2_0_9], [5_6_9, 1_9_6, 5_9_5, 2_0_8], [6_1_0, 1_9_6, 7_0_2, 2_0_9], [5_0_5, 2_1_4, 5_8_3, 2_2_6], [5_9_5, 2_1_4, 6_5_6, 2_2_7], [6_7_0, 2_1_5, 8_0_7, 2_2_7], [3_3_5, 2_5_9, 5_4_3, 2_7_4], [5_5_6, 2_5_9, 7_0_8, 2_7_2], [3_7_2, 2_7_9, 4_2_2, 2_9_1], [4_3_5, 2_7_9, 4_6_0, 2_9_1], [4_7_4, 2_7_9, 5_7_4, 2_9_2], [5_8_7, 2_7_8, 6_6_4, 2_9_1], [6_7_6, 2_7_8, 7_3_8, 2_9_1], [7_5_1, 2_7_9, 8_3_4, 2_9_1], [3_7_2, 2_9_8, 4_3_4, 3_1_0], [3_3_5, 3_4_1, 4_8_3, 3_5_4], [4_9_7, 3_4_1, 6_5_5, 3_5_4], [6_6_7, 3_4_1, 7_2_8, 3_5_4], [7_4_0, 3_4_1, 8_2_5, 3_5_4], [3_3_5, 3_6_0, 4_3_0, 3_7_2], [4_4_2, 3_6_0, 5_3_4, 3_7_2], [5_4_5, 3_5_9, 6_8_7, 3_7_2], [6_9_7, 3_6_0, 7_5_4, 3_7_2], [7_6_5, 3_6_0, 8_2_3, 3_7_3], [3_3_4, 3_7_8, 4_2_8, 3_9_1], [4_4_0, 3_7_8, 5_7_7, 3_9_4], [5_9_0, 3_7_8, 7_0_5, 3_9_1], [7_2_0, 3_7_8, 8_0_1, 3_9_1], [3_3_4, 3_9_7, 4_0_0, 4_0_9], [3_7_0, 4_1_6, 5_2_9, 4_2_9], [5_4_4, 4_1_6, 5_7_6, 4_3_2], [5_8_7, 4_1_6, 6_6_5, 4_2_8], [6_7_7, 4_1_6, 8_1_4, 4_2_9], [3_7_2, 4_3_5, 4_5_2, 4_5_0], [4_6_5, 4_3_4, 4_9_5, 4_4_7], [5_1_1, 4_3_4, 6_0_0, 4_4_7], [6_1_1, 4_3_6, 6_3_7, 4_4_7], [6_4_9, 4_3_6, 6_9_4, 4_5_1], [7_0_5, 4_3_8, 8_2_4, 4_4_7], [3_6_9, 4_5_3, 4_5_2, 4_6_6], [4_6_4, 4_5_4, 5_0_9, 4_6_6], [5_2_2, 4_5_3, 6_1_1, 4_6_9], [6_2_5, 4_5_3, 7_9_2, 4_6_9], [3_7_0, 4_7_2, 5_5_6, 4_8_8], [5_7_0, 4_7_2, 6_8_4, 4_8_7], [6_9_7, 4_7_2, 7_1_8, 4_8_5], [7_3_2, 4_7_2, 8_3_5, 4_8_8], [3_6_9, 4_9_0, 4_1_1, 5_0_3], [4_2_5, 4_9_0, 4_8_4, 5_0_3], [4_9_6, 4_9_0, 6_3_5, 5_0_6], [6_4_5, 4_9_0, 7_0_7, 5_0_3], [7_1_8, 4_9_1, 7_6_1, 5_0_3], [7_7_1, 4_9_0, 8_4_0, 5_0_3], [3_3_6, 5_1_0, 3_7_4, 5_2_1], [3_8_8, 5_1_0, 4_4_7, 5_2_2], [4_6_0, 5_1_0, 4_8_9, 5_2_1], [5_0_3, 5_1_0, 5_8_0, 5_2_2], [5_9_2, 5_0_9, 7_3_6, 5_2_5], [7_4_5, 5_0_9, 7_7_0, 5_2_2], [7_8_1, 5_0_9, 8_4_0, 5_2_2], [3_3_8, 5_2_8, 4_3_4, 5_4_1], [4_4_8, 5_2_8, 5_9_6, 5_4_1], [6_0_9, 5_2_7, 6_8_7, 5_4_0], [7_0_0, 5_2_8, 7_9_2, 5_4_1], [3_3_6, 5_4_6, 3_9_7, 5_5_9], [4_0_7, 5_4_6, 4_3_1, 5_5_9], [4_4_3, 5_4_6, 5_2_5, 5_6_0], [5_3_7, 5_4_6, 6_8_0, 5_6_2], [6_8_8, 5_4_6, 7_1_4, 5_5_9], [7_2_2, 5_4_6, 8_3_7, 5_6_2], [3_3_6, 5_6_5, 4_4_9, 5_8_1], [4_6_1, 5_6_5, 4_8_5, 5_7_7], [4_9_7, 5_6_5, 6_6_5, 5_8_1], [6_8_1, 5_6_5, 7_1_8, 5_7_7], [7_3_2, 5_6_5, 8_3_7, 5_8_0], [3_3_7, 5_8_4, 4_3_8, 5_9_7], [4_5_2, 5_8_3, 5_2_1, 5_9_6], [5_3_5, 5_8_4, 6_7_7, 5_9_9], [6_9_0, 5_8_3, 7_8_7, 5_9_6], [8_0_1, 5_8_3, 8_2_5, 5_9_6], [3_3_8, 6_0_2, 4_7_8, 6_1_5], [4_9_2, 6_0_2, 5_3_0, 6_1_4], [5_4_3, 6_0_2, 6_3_8, 6_1_5], [6_5_0, 6_0_2, 6_7_6, 6_1_4], [6_8_8, 6_0_2, 7_8_8, 6_1_5], [8_0_2, 6_0_2, 8_4_3, 6_1_4], [3_3_7, 6_2_1, 5_0_2, 6_3_3], [5_1_6, 6_2_1, 6_1_5, 6_3_7], [6_2_9, 6_2_1, 7_7_4, 6_3_6], [7_8_9, 6_2_1, 8_2_7, 6_3_3], [3_3_7, 6_3_9, 4_1_8, 6_5_2], [4_3_2, 6_4_0, 5_7_1, 6_5_3], [5_8_7, 6_3_9, 7_3_1, 6_5_5], [7_4_3, 6_3_9, 7_6_9, 6_5_2], [7_8_0, 6_3_9, 8_4_1, 6_5_2], [3_3_8, 6_5_8, 4_4_0, 6_7_3], [4_5_5, 6_5_8, 4_9_1, 6_7_0], [5_0_8, 6_5_8, 6_0_2, 6_7_1], [6_1_6, 6_5_8, 6_3_8, 6_7_0], [6_5_4, 6_5_8, 8_3_5, 6_7_4], [3_3_7, 6_7_7, 4_2_9, 6_8_9], [3_3_7, 7_1_4, 4_8_2, 7_2_6], [4_9_5, 7_1_4, 5_4_8, 7_2_6], [5_6_1, 7_1_4, 6_8_3, 7_2_6], [3_3_8, 7_7_0, 4_6_1, 7_8_2], [4_7_4, 7_6_9, 5_5_4, 7_8_5], [4_8_9, 7_8_8, 5_6_2, 8_0_3], [5_7_6, 7_8_8, 6_4_3, 8_0_1], [6_5_6, 7_8_7, 7_5_1, 8_0_4], [7_6_4, 7_8_8, 8_4_4, 8_0_1], [3_3_4, 8_2_5, 4_2_1, 8_3_8], [4_3_0, 8_2_4, 5_7_4, 8_3_8], [5_8_4, 8_2_4, 7_2_3, 8_4_1], [3_3_5, 8_4_4, 4_5_0, 8_5_7], [4_6_4, 8_4_3, 5_8_3, 8_6_0], [6_2_8, 8_6_2, 7_5_5, 8_7_5], [7_6_9, 8_6_1, 8_4_8, 8_7_8]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(encoding.boxes , SCREAMING_SNAKE_CASE__ ) # with apply_OCR = False A_ : Optional[Any] = LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE__ ) A_ : List[str] = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_2_4, 2_2_4) )
558
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 __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) 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(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) 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" , )
61
0
"""simple docstring""" import sys UpperCAmelCase = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def __magic_name__ ( _lowerCamelCase: str = N ) -> Any: '''simple docstring''' lowerCAmelCase = -sys.maxsize - 1 for i in range(len(lowerCAmelCase_ ) - 12 ): lowerCAmelCase = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: lowerCAmelCase = product return largest_product if __name__ == "__main__": print(f"""{solution() = }""")
535
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __UpperCamelCase : Tuple = logging.get_logger(__name__) class __UpperCamelCase ( UpperCamelCase__ ): __snake_case :Dict = ['pixel_values'] def __init__( self : str , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[Dict[str, int]] = None , _lowerCAmelCase : PILImageResampling = PILImageResampling.BILINEAR , _lowerCAmelCase : bool = True , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : bool = True , _lowerCAmelCase : Union[int, float] = 1 / 255 , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , **_lowerCAmelCase : int , ) -> None: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) __lowercase = size if size is not None else {"""shortest_edge""": 256} __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) __lowercase = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ ) __lowercase = do_resize __lowercase = size __lowercase = resample __lowercase = do_center_crop __lowercase = crop_size __lowercase = do_rescale __lowercase = rescale_factor __lowercase = do_normalize __lowercase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __lowercase = image_std if image_std is not None else IMAGENET_STANDARD_STD def _a ( self : List[Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Dict[str, int] , _lowerCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : List[Any] , ) -> np.ndarray: """simple docstring""" __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __lowercase = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=size["""shortest_edge"""] , default_to_square=SCREAMING_SNAKE_CASE__ ) return resize(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _a ( self : str , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Dict[str, int] , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : Tuple , ) -> np.ndarray: """simple docstring""" __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ ) return center_crop(SCREAMING_SNAKE_CASE__ , size=(size["""height"""], size["""width"""]) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _a ( self : Optional[Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : float , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : str ) -> np.ndarray: """simple docstring""" return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _a ( self : Optional[Any] , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : Union[float, List[float]] , _lowerCAmelCase : Union[float, List[float]] , _lowerCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_lowerCAmelCase : Any , ) -> np.ndarray: """simple docstring""" return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _a ( self : List[Any] , _lowerCAmelCase : ImageInput , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : PILImageResampling = None , _lowerCAmelCase : bool = None , _lowerCAmelCase : Dict[str, int] = None , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Optional[float] = None , _lowerCAmelCase : Optional[bool] = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : Optional[Union[float, List[float]]] = None , _lowerCAmelCase : Optional[Union[str, TensorType]] = None , _lowerCAmelCase : Union[str, ChannelDimension] = ChannelDimension.FIRST , **_lowerCAmelCase : Optional[Any] , ) -> List[Any]: """simple docstring""" __lowercase = do_resize if do_resize is not None else self.do_resize __lowercase = size if size is not None else self.size __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) __lowercase = resample if resample is not None else self.resample __lowercase = do_center_crop if do_center_crop is not None else self.do_center_crop __lowercase = crop_size if crop_size is not None else self.crop_size __lowercase = get_size_dict(SCREAMING_SNAKE_CASE__ ) __lowercase = do_rescale if do_rescale is not None else self.do_rescale __lowercase = rescale_factor if rescale_factor is not None else self.rescale_factor __lowercase = do_normalize if do_normalize is not None else self.do_normalize __lowercase = image_mean if image_mean is not None else self.image_mean __lowercase = image_std if image_std is not None else self.image_std __lowercase = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # All transformations expect numpy arrays. __lowercase = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: __lowercase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: __lowercase = [self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: __lowercase = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: __lowercase = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] __lowercase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] __lowercase = {"""pixel_values""": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
80
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
0
'''simple docstring''' def A_ ( _lowerCAmelCase : str , _lowerCAmelCase : str ): """simple docstring""" if len(lowerCAmelCase_ ) != len(lowerCAmelCase_ ): raise ValueError("String lengths must match!" ) _lowerCamelCase : int = 0 for chara, chara in zip(lowerCAmelCase_ , lowerCAmelCase_ ): if chara != chara: count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
44
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
0
import random def snake_case__ ( SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Any ): '''simple docstring''' lowercase__ : List[Any] = a[left_index] lowercase__ : List[Any] = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowercase__ , lowercase__ : Union[str, Any] = a[i], a[j] i += 1 lowercase__ , lowercase__ : List[str] = a[i - 1], a[left_index] return i - 1 def snake_case__ ( SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' if left < right: lowercase__ : List[Any] = random.randint(lowerCAmelCase_ , right - 1 ) lowercase__ , lowercase__ : Any = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowercase__ : Tuple = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def snake_case__ ( ): '''simple docstring''' lowercase__ : Optional[Any] = input('Enter numbers separated by a comma:\n' ).strip() lowercase__ : str = [int(lowerCAmelCase_ ) for item in user_input.split(',' )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
164
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
0
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification a = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co a = 'main' # Default branch name a = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) a = 'aaaaaaa' # This commit does not exist, so we should 404. a = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes a = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def lowercase () -> Union[str, Any]: '''simple docstring''' print("""Welcome!""" ) yield print("""Bye!""" ) @contextlib.contextmanager def lowercase () -> int: '''simple docstring''' print("""Bonjour!""" ) yield print("""Au revoir!""" ) class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("""transformers""" ) is not None class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowercase ( self : Any , lowerCAmelCase : int ): with ContextManagers([] ): print("""Transformers are awesome!""" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , """Transformers are awesome!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowercase ( self : Any , lowerCAmelCase : Optional[int] ): with ContextManagers([context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Welcome!\nTransformers are awesome!\nBye!\n""" ) @unittest.mock.patch("""sys.stdout""" , new_callable=io.StringIO ) def __lowercase ( self : Dict , lowerCAmelCase : Optional[Any] ): with ContextManagers([context_fr(), context_en()] ): print("""Transformers are awesome!""" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , """Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n""" ) @require_torch def __lowercase ( self : Optional[Any] ): self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels"""] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""start_positions""", """end_positions"""] ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels"""] ) @require_tf def __lowercase ( self : Optional[int] ): self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels"""] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels""", """next_sentence_label"""] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""start_positions""", """end_positions"""] ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , ["""labels"""] ) @require_flax def __lowercase ( self : Optional[Any] ): # Flax models don't have labels self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): pass self.assertEqual(find_labels(SCREAMING_SNAKE_CASE__ ) , [] )
169
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
0
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase =logging.get_logger(__name__) _lowerCamelCase ={ """facebook/s2t-small-librispeech-asr""": ( """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json""" ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class A__ ( UpperCamelCase__): _UpperCAmelCase : int = """speech_to_text""" _UpperCAmelCase : Optional[int] = ["""past_key_values"""] _UpperCAmelCase : int = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , __magic_name__=1_0_0_0_0 , __magic_name__=1_2 , __magic_name__=2_0_4_8 , __magic_name__=4 , __magic_name__=6 , __magic_name__=2_0_4_8 , __magic_name__=4 , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=True , __magic_name__=True , __magic_name__="relu" , __magic_name__=2_5_6 , __magic_name__=0.1 , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=0.02 , __magic_name__=2 , __magic_name__=True , __magic_name__=1 , __magic_name__=0 , __magic_name__=2 , __magic_name__=6_0_0_0 , __magic_name__=1_0_2_4 , __magic_name__=2 , __magic_name__=(5, 5) , __magic_name__=1_0_2_4 , __magic_name__=8_0 , __magic_name__=1 , **__magic_name__ , ): lowerCamelCase : List[str] = vocab_size lowerCamelCase : str = d_model lowerCamelCase : Any = encoder_ffn_dim lowerCamelCase : Tuple = encoder_layers lowerCamelCase : List[Any] = encoder_attention_heads lowerCamelCase : str = decoder_ffn_dim lowerCamelCase : Dict = decoder_layers lowerCamelCase : Dict = decoder_attention_heads lowerCamelCase : int = dropout lowerCamelCase : Union[str, Any] = attention_dropout lowerCamelCase : Union[str, Any] = activation_dropout lowerCamelCase : Optional[int] = activation_function lowerCamelCase : Optional[int] = init_std lowerCamelCase : Dict = encoder_layerdrop lowerCamelCase : List[str] = decoder_layerdrop lowerCamelCase : List[Any] = use_cache lowerCamelCase : Any = encoder_layers lowerCamelCase : Dict = scale_embedding # scale factor will be sqrt(d_model) if True lowerCamelCase : Optional[Any] = max_source_positions lowerCamelCase : int = max_target_positions lowerCamelCase : Any = num_conv_layers lowerCamelCase : int = list(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Optional[Any] = conv_channels lowerCamelCase : Dict = input_feat_per_channel lowerCamelCase : Optional[int] = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( """Configuration for convolutional module is incorrect. """ """It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` """ F'''but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, ''' F'''`config.num_conv_layers = {self.num_conv_layers}`.''' ) 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__ , **SCREAMING_SNAKE_CASE__ , )
681
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
0
'''simple docstring''' def __UpperCAmelCase ( __magic_name__ ,__magic_name__ )-> Dict: """simple docstring""" if a < 0 or b < 0: raise ValueError("the value of both inputs must be positive" ) snake_case_ : Union[str, Any] = str(bin(lowerCAmelCase_ ) )[2:] # remove the leading "0b" snake_case_ : List[str] = str(bin(lowerCAmelCase_ ) )[2:] # remove the leading "0b" snake_case_ : Dict = max(len(lowerCAmelCase_ ) ,len(lowerCAmelCase_ ) ) return "0b" + "".join( str(int(char_a == "1" and char_b == "1" ) ) for char_a, char_b in zip(a_binary.zfill(lowerCAmelCase_ ) ,b_binary.zfill(lowerCAmelCase_ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
653
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def __a(SCREAMING_SNAKE_CASE_ : str ): '''simple docstring''' _lowerCAmelCase = DPTConfig(embedding_type="hybrid" ) if "large" in checkpoint_url: _lowerCAmelCase = 1024 _lowerCAmelCase = 4096 _lowerCAmelCase = 24 _lowerCAmelCase = 16 _lowerCAmelCase = [5, 11, 17, 23] _lowerCAmelCase = [256, 512, 1024, 1024] _lowerCAmelCase = (1, 384, 384) if "nyu" or "midas" in checkpoint_url: _lowerCAmelCase = 768 _lowerCAmelCase = [1, 1, 1, 0.5] _lowerCAmelCase = [256, 512, 768, 768] _lowerCAmelCase = 150 _lowerCAmelCase = 16 _lowerCAmelCase = (1, 384, 384) _lowerCAmelCase = False _lowerCAmelCase = "project" if "ade" in checkpoint_url: _lowerCAmelCase = True _lowerCAmelCase = 768 _lowerCAmelCase = [1, 1, 1, 0.5] _lowerCAmelCase = 150 _lowerCAmelCase = 16 _lowerCAmelCase = "huggingface/label-files" _lowerCAmelCase = "ade20k-id2label.json" _lowerCAmelCase = json.load(open(cached_download(hf_hub_url(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) ) , "r" ) ) _lowerCAmelCase = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} _lowerCAmelCase = idalabel _lowerCAmelCase = {v: k for k, v in idalabel.items()} _lowerCAmelCase = [1, 150, 480, 480] return config, expected_shape def __a(SCREAMING_SNAKE_CASE_ : List[Any] ): '''simple docstring''' _lowerCAmelCase = ["pretrained.model.head.weight", "pretrained.model.head.bias"] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def __a(SCREAMING_SNAKE_CASE_ : Optional[int] ): '''simple docstring''' if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): _lowerCAmelCase = name.replace("pretrained.model" , "dpt.encoder" ) if "pretrained.model" in name: _lowerCAmelCase = name.replace("pretrained.model" , "dpt.embeddings" ) if "patch_embed" in name: _lowerCAmelCase = name.replace("patch_embed" , "" ) if "pos_embed" in name: _lowerCAmelCase = name.replace("pos_embed" , "position_embeddings" ) if "attn.proj" in name: _lowerCAmelCase = name.replace("attn.proj" , "attention.output.dense" ) if "proj" in name and "project" not in name: _lowerCAmelCase = name.replace("proj" , "projection" ) if "blocks" in name: _lowerCAmelCase = name.replace("blocks" , "layer" ) if "mlp.fc1" in name: _lowerCAmelCase = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: _lowerCAmelCase = name.replace("mlp.fc2" , "output.dense" ) if "norm1" in name and "backbone" not in name: _lowerCAmelCase = name.replace("norm1" , "layernorm_before" ) if "norm2" in name and "backbone" not in name: _lowerCAmelCase = name.replace("norm2" , "layernorm_after" ) if "scratch.output_conv" in name: _lowerCAmelCase = name.replace("scratch.output_conv" , "head" ) if "scratch" in name: _lowerCAmelCase = name.replace("scratch" , "neck" ) if "layer1_rn" in name: _lowerCAmelCase = name.replace("layer1_rn" , "convs.0" ) if "layer2_rn" in name: _lowerCAmelCase = name.replace("layer2_rn" , "convs.1" ) if "layer3_rn" in name: _lowerCAmelCase = name.replace("layer3_rn" , "convs.2" ) if "layer4_rn" in name: _lowerCAmelCase = name.replace("layer4_rn" , "convs.3" ) if "refinenet" in name: _lowerCAmelCase = int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 _lowerCAmelCase = name.replace(F'''refinenet{layer_idx}''' , F'''fusion_stage.layers.{abs(layer_idx-4 )}''' ) if "out_conv" in name: _lowerCAmelCase = name.replace("out_conv" , "projection" ) if "resConfUnit1" in name: _lowerCAmelCase = name.replace("resConfUnit1" , "residual_layer1" ) if "resConfUnit2" in name: _lowerCAmelCase = name.replace("resConfUnit2" , "residual_layer2" ) if "conv1" in name: _lowerCAmelCase = name.replace("conv1" , "convolution1" ) if "conv2" in name: _lowerCAmelCase = name.replace("conv2" , "convolution2" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess1.0.project.0" , "neck.reassemble_stage.readout_projects.0.0" ) if "pretrained.act_postprocess2.0.project.0" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess2.0.project.0" , "neck.reassemble_stage.readout_projects.1.0" ) if "pretrained.act_postprocess3.0.project.0" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess3.0.project.0" , "neck.reassemble_stage.readout_projects.2.0" ) if "pretrained.act_postprocess4.0.project.0" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess4.0.project.0" , "neck.reassemble_stage.readout_projects.3.0" ) # resize blocks if "pretrained.act_postprocess1.3" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess1.3" , "neck.reassemble_stage.layers.0.projection" ) if "pretrained.act_postprocess1.4" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess1.4" , "neck.reassemble_stage.layers.0.resize" ) if "pretrained.act_postprocess2.3" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess2.3" , "neck.reassemble_stage.layers.1.projection" ) if "pretrained.act_postprocess2.4" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess2.4" , "neck.reassemble_stage.layers.1.resize" ) if "pretrained.act_postprocess3.3" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess3.3" , "neck.reassemble_stage.layers.2.projection" ) if "pretrained.act_postprocess4.3" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess4.3" , "neck.reassemble_stage.layers.3.projection" ) if "pretrained.act_postprocess4.4" in name: _lowerCAmelCase = name.replace("pretrained.act_postprocess4.4" , "neck.reassemble_stage.layers.3.resize" ) if "pretrained" in name: _lowerCAmelCase = name.replace("pretrained" , "dpt" ) if "bn" in name: _lowerCAmelCase = name.replace("bn" , "batch_norm" ) if "head" in name: _lowerCAmelCase = name.replace("head" , "head.head" ) if "encoder.norm" in name: _lowerCAmelCase = name.replace("encoder.norm" , "layernorm" ) if "auxlayer" in name: _lowerCAmelCase = name.replace("auxlayer" , "auxiliary_head.head" ) if "backbone" in name: _lowerCAmelCase = name.replace("backbone" , "backbone.bit.encoder" ) if ".." in name: _lowerCAmelCase = name.replace(".." , "." ) if "stem.conv" in name: _lowerCAmelCase = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: _lowerCAmelCase = name.replace("blocks" , "layers" ) if "convolution" in name and "backbone" in name: _lowerCAmelCase = name.replace("convolution" , "conv" ) if "layer" in name and "backbone" in name: _lowerCAmelCase = name.replace("layer" , "layers" ) if "backbone.bit.encoder.bit" in name: _lowerCAmelCase = name.replace("backbone.bit.encoder.bit" , "backbone.bit" ) if "embedder.conv" in name: _lowerCAmelCase = name.replace("embedder.conv" , "embedder.convolution" ) if "backbone.bit.encoder.stem.norm" in name: _lowerCAmelCase = name.replace("backbone.bit.encoder.stem.norm" , "backbone.bit.embedder.norm" ) return name def __a(SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] ): '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _lowerCAmelCase = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.weight''' ) _lowerCAmelCase = state_dict.pop(F'''dpt.encoder.layer.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _lowerCAmelCase = in_proj_weight[: config.hidden_size, :] _lowerCAmelCase = in_proj_bias[: config.hidden_size] _lowerCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _lowerCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _lowerCAmelCase = in_proj_weight[ -config.hidden_size :, : ] _lowerCAmelCase = in_proj_bias[-config.hidden_size :] def __a(): '''simple docstring''' _lowerCAmelCase = "http://images.cocodataset.org/val2017/000000039769.jpg" _lowerCAmelCase = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def __a(SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ): '''simple docstring''' _lowerCAmelCase , _lowerCAmelCase = get_dpt_config(lowerCAmelCase_ ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") _lowerCAmelCase = torch.load(lowerCAmelCase_ , map_location="cpu" ) # remove certain keys remove_ignore_keys_(lowerCAmelCase_ ) # rename keys for key in state_dict.copy().keys(): _lowerCAmelCase = state_dict.pop(lowerCAmelCase_ ) _lowerCAmelCase = val # read in qkv matrices read_in_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ ) # load HuggingFace model _lowerCAmelCase = DPTForSemanticSegmentation(lowerCAmelCase_ ) if "ade" in checkpoint_url else DPTForDepthEstimation(lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) model.eval() # Check outputs on an image _lowerCAmelCase = 480 if "ade" in checkpoint_url else 384 _lowerCAmelCase = DPTImageProcessor(size=lowerCAmelCase_ ) _lowerCAmelCase = prepare_img() _lowerCAmelCase = image_processor(lowerCAmelCase_ , return_tensors="pt" ) # forward pass _lowerCAmelCase = model(**lowerCAmelCase_ ).logits if "ade" in checkpoint_url else model(**lowerCAmelCase_ ).predicted_depth if show_prediction: _lowerCAmelCase = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode="bicubic" , align_corners=lowerCAmelCase_ , ) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 255 ).show() if pytorch_dump_folder_path is not None: Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowerCAmelCase_ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowerCAmelCase_ ) if push_to_hub: model.push_to_hub("ybelkada/dpt-hybrid-midas" ) image_processor.push_to_hub("ybelkada/dpt-hybrid-midas" ) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt", type=str, help="URL of the original DPT checkpoint you\'d like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=False, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", ) parser.add_argument( "--model_name", default="dpt-large", type=str, help="Name of the model, in case you\'re pushing to the hub.", ) parser.add_argument( "--show_prediction", action="store_true", ) _SCREAMING_SNAKE_CASE = parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
18
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
"""simple docstring""" import cva import numpy as np class _UpperCAmelCase : """simple docstring""" def __init__( self , _lowercase , _lowercase ) -> Optional[Any]: if k in (0.04, 0.06): _lowerCamelCase : List[Any] = k _lowerCamelCase : str = window_size else: raise ValueError('''invalid k value''' ) def __str__( self ) -> str: return str(self.k ) def a__ ( self , _lowercase ) -> tuple[cva.Mat, list[list[int]]]: _lowerCamelCase : str = cva.imread(SCREAMING_SNAKE_CASE__ , 0 ) _lowerCamelCase, _lowerCamelCase : Optional[Any] = img.shape _lowerCamelCase : Dict = [] _lowerCamelCase : int = img.copy() _lowerCamelCase : int = cva.cvtColor(SCREAMING_SNAKE_CASE__ , cva.COLOR_GRAY2RGB ) _lowerCamelCase, _lowerCamelCase : List[Any] = np.gradient(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : List[str] = dx**2 _lowerCamelCase : int = dy**2 _lowerCamelCase : Union[str, Any] = dx * dy _lowerCamelCase : Dict = 0.04 _lowerCamelCase : int = self.window_size // 2 for y in range(SCREAMING_SNAKE_CASE__ , h - offset ): for x in range(SCREAMING_SNAKE_CASE__ , w - offset ): _lowerCamelCase : int = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _lowerCamelCase : Dict = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _lowerCamelCase : List[Any] = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() _lowerCamelCase : str = (wxx * wyy) - (wxy**2) _lowerCamelCase : Union[str, Any] = wxx + wyy _lowerCamelCase : Optional[int] = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple =HarrisCorner(0.04, 3) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] =edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
434
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
"""simple docstring""" from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _snake_case = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class _SCREAMING_SNAKE_CASE ( UpperCamelCase__ ): '''simple docstring''' def __init__( self : Optional[int] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : Tuple ) -> Dict: """simple docstring""" super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def __lowerCamelCase ( self : Tuple , UpperCAmelCase_ : Union[str, Any]=None ) -> Optional[int]: """simple docstring""" _lowerCAmelCase = {} if top_k is not None: _lowerCAmelCase = top_k return {}, {}, postprocess_params def __call__( self : Any , UpperCAmelCase_ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **UpperCAmelCase_ : str ) -> Dict: """simple docstring""" return super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def __lowerCamelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" _lowerCAmelCase = load_image(SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase = self.image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors=self.framework ) return model_inputs def __lowerCamelCase ( self : int , UpperCAmelCase_ : int ) -> List[Any]: """simple docstring""" _lowerCAmelCase = self.model(**SCREAMING_SNAKE_CASE__ ) return model_outputs def __lowerCamelCase ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : int=5 ) -> str: """simple docstring""" if top_k > self.model.config.num_labels: _lowerCAmelCase = self.model.config.num_labels if self.framework == "pt": _lowerCAmelCase = model_outputs.logits.softmax(-1 )[0] _lowerCAmelCase , _lowerCAmelCase = probs.topk(SCREAMING_SNAKE_CASE__ ) elif self.framework == "tf": _lowerCAmelCase = stable_softmax(model_outputs.logits , axis=-1 )[0] _lowerCAmelCase = tf.math.top_k(SCREAMING_SNAKE_CASE__ , k=SCREAMING_SNAKE_CASE__ ) _lowerCAmelCase , _lowerCAmelCase = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) _lowerCAmelCase = scores.tolist() _lowerCAmelCase = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )]
580
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def UpperCamelCase ( __lowercase : str ,__lowercase : str ,**__lowercase : Union[str, Any] ): '''simple docstring''' A_ : int = AutoConfig.from_pretrained(lowerCAmelCase_ ,**lowerCAmelCase_ ) A_ : Optional[int] = AutoModelForSeqaSeqLM.from_config(lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) AutoTokenizer.from_pretrained(lowerCAmelCase_ ).save_pretrained(lowerCAmelCase_ ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
558
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCAmelCase = logging.get_logger(__name__) class lowercase ( UpperCamelCase__ ): def __init__(self : List[Any] ,*SCREAMING_SNAKE_CASE_ : str ,**SCREAMING_SNAKE_CASE_ : Optional[int] ) -> None: """simple docstring""" warnings.warn( '''The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please''' ''' use FlavaImageProcessor instead.''' ,SCREAMING_SNAKE_CASE__ ,) super().__init__(*SCREAMING_SNAKE_CASE__ ,**SCREAMING_SNAKE_CASE__ )
535
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' if index == r: for j in range(lowerCAmelCase_ ): print(data[j] , end=""" """ ) print(""" """ ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __lowercase = arr[i] combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , index + 1 , lowerCAmelCase_ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' __lowercase = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , 0 , lowerCAmelCase_ , 0 ) if __name__ == "__main__": # Driver code to check the function above __UpperCamelCase : Optional[int] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
80
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = 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 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def A_ ( _lowerCAmelCase : Optional[int] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = SwinConfig() _lowerCamelCase : Union[str, Any] = swin_name.split("_" ) _lowerCamelCase : Optional[Any] = name_split[1] _lowerCamelCase : Optional[int] = int(name_split[4] ) _lowerCamelCase : List[str] = int(name_split[3][-1] ) if model_size == "tiny": _lowerCamelCase : Tuple = 96 _lowerCamelCase : Optional[Any] = (2, 2, 6, 2) _lowerCamelCase : int = (3, 6, 12, 24) elif model_size == "small": _lowerCamelCase : Optional[int] = 96 _lowerCamelCase : Dict = (2, 2, 18, 2) _lowerCamelCase : Dict = (3, 6, 12, 24) elif model_size == "base": _lowerCamelCase : Union[str, Any] = 128 _lowerCamelCase : List[str] = (2, 2, 18, 2) _lowerCamelCase : Any = (4, 8, 16, 32) else: _lowerCamelCase : List[str] = 192 _lowerCamelCase : str = (2, 2, 18, 2) _lowerCamelCase : int = (6, 12, 24, 48) if "in22k" in swin_name: _lowerCamelCase : Optional[int] = 21841 else: _lowerCamelCase : Optional[int] = 1000 _lowerCamelCase : int = "huggingface/label-files" _lowerCamelCase : Optional[Any] = "imagenet-1k-id2label.json" _lowerCamelCase : Tuple = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type="dataset" ) , "r" ) ) _lowerCamelCase : int = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} _lowerCamelCase : int = idalabel _lowerCamelCase : Union[str, Any] = {v: k for k, v in idalabel.items()} _lowerCamelCase : Any = img_size _lowerCamelCase : Optional[int] = num_classes _lowerCamelCase : Union[str, Any] = embed_dim _lowerCamelCase : Optional[int] = depths _lowerCamelCase : Dict = num_heads _lowerCamelCase : Optional[Any] = window_size return config def A_ ( _lowerCAmelCase : int ): """simple docstring""" if "patch_embed.proj" in name: _lowerCamelCase : Optional[Any] = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: _lowerCamelCase : str = name.replace("patch_embed.norm" , "embeddings.norm" ) if "layers" in name: _lowerCamelCase : Optional[Any] = "encoder." + name if "attn.proj" in name: _lowerCamelCase : Dict = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: _lowerCamelCase : Optional[int] = name.replace("attn" , "attention.self" ) if "norm1" in name: _lowerCamelCase : Dict = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: _lowerCamelCase : List[str] = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: _lowerCamelCase : Dict = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: _lowerCamelCase : Tuple = name.replace("mlp.fc2" , "output.dense" ) if name == "norm.weight": _lowerCamelCase : Optional[int] = "layernorm.weight" if name == "norm.bias": _lowerCamelCase : Any = "layernorm.bias" if "head" in name: _lowerCamelCase : Optional[Any] = name.replace("head" , "classifier" ) else: _lowerCamelCase : Optional[int] = "swin." + name return name def A_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any] ): """simple docstring""" for key in orig_state_dict.copy().keys(): _lowerCamelCase : Tuple = orig_state_dict.pop(lowerCAmelCase_ ) if "mask" in key: continue elif "qkv" in key: _lowerCamelCase : List[Any] = key.split("." ) _lowerCamelCase : Union[str, Any] = int(key_split[1] ) _lowerCamelCase : int = int(key_split[3] ) _lowerCamelCase : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: _lowerCamelCase : Optional[int] = val[:dim, :] _lowerCamelCase : List[Any] = val[ dim : dim * 2, : ] _lowerCamelCase : Optional[Any] = val[-dim:, :] else: _lowerCamelCase : str = val[ :dim ] _lowerCamelCase : Union[str, Any] = val[ dim : dim * 2 ] _lowerCamelCase : Optional[Any] = val[ -dim: ] else: _lowerCamelCase : List[str] = val return orig_state_dict def A_ ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any] ): """simple docstring""" _lowerCamelCase : Tuple = timm.create_model(lowerCAmelCase_ , pretrained=lowerCAmelCase_ ) timm_model.eval() _lowerCamelCase : int = get_swin_config(lowerCAmelCase_ ) _lowerCamelCase : Optional[Any] = SwinForImageClassification(lowerCAmelCase_ ) model.eval() _lowerCamelCase : Dict = convert_state_dict(timm_model.state_dict() , lowerCAmelCase_ ) model.load_state_dict(lowerCAmelCase_ ) _lowerCamelCase : str = "http://images.cocodataset.org/val2017/000000039769.jpg" _lowerCamelCase : int = AutoImageProcessor.from_pretrained("microsoft/{}".format(swin_name.replace("_" , "-" ) ) ) _lowerCamelCase : int = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) _lowerCamelCase : Any = image_processor(images=lowerCAmelCase_ , return_tensors="pt" ) _lowerCamelCase : Optional[Any] = timm_model(inputs["pixel_values"] ) _lowerCamelCase : Any = model(**lowerCAmelCase_ ).logits assert torch.allclose(lowerCAmelCase_ , lowerCAmelCase_ , atol=1E-3 ) print(F'Saving model {swin_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase_ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": UpperCAmelCase_ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) UpperCAmelCase_ : int = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
44
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case_ = logging.get_logger(__name__) snake_case_ = { '''Salesforce/blip-vqa-base''': '''https://huggingface.co/Salesforce/blip-vqa-base/resolve/main/config.json''', '''Salesforce/blip-vqa-capfit-large''': ( '''https://huggingface.co/Salesforce/blip-vqa-base-capfit/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-base''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-base/resolve/main/config.json''' ), '''Salesforce/blip-image-captioning-large''': ( '''https://huggingface.co/Salesforce/blip-image-captioning-large/resolve/main/config.json''' ), '''Salesforce/blip-itm-base-coco''': '''https://huggingface.co/Salesforce/blip-itm-base-coco/resolve/main/config.json''', '''Salesforce/blip-itm-large-coco''': '''https://huggingface.co/Salesforce/blip-itm-large-coco/resolve/main/config.json''', '''Salesforce/blip-itm-base-flikr''': '''https://huggingface.co/Salesforce/blip-itm-base-flikr/resolve/main/config.json''', '''Salesforce/blip-itm-large-flikr''': ( '''https://huggingface.co/Salesforce/blip-itm-large-flikr/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE__ (UpperCamelCase__ ): __lowerCamelCase : Dict = """blip_text_model""" def __init__( self , a=3_0524 , a=768 , a=768 , a=3072 , a=768 , a=12 , a=8 , a=512 , a="gelu" , a=1e-12 , a=0.0 , a=0.0 , a=0.02 , a=3_0522 , a=2 , a=0 , a=102 , a=True , a=True , **a , ): super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , sep_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowercase__ : Optional[Any] = vocab_size lowercase__ : Any = hidden_size lowercase__ : str = encoder_hidden_size lowercase__ : Any = intermediate_size lowercase__ : Optional[Any] = projection_dim lowercase__ : Optional[Any] = hidden_dropout_prob lowercase__ : Dict = num_hidden_layers lowercase__ : int = num_attention_heads lowercase__ : str = max_position_embeddings lowercase__ : Optional[int] = layer_norm_eps lowercase__ : Optional[int] = hidden_act lowercase__ : Dict = initializer_range lowercase__ : Optional[int] = attention_probs_dropout_prob lowercase__ : str = is_decoder lowercase__ : Optional[int] = use_cache @classmethod def snake_case_ ( cls , a , **a): cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__) lowercase__ , lowercase__ : Optional[int] = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) # get the text config dict if we are loading from BlipConfig if config_dict.get('model_type') == "blip": lowercase__ : Optional[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(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) class SCREAMING_SNAKE_CASE__ (UpperCamelCase__ ): __lowerCamelCase : Tuple = """blip_vision_model""" def __init__( self , a=768 , a=3072 , a=512 , a=12 , a=12 , a=384 , a=16 , a="gelu" , a=1e-5 , a=0.0 , a=1e-10 , **a , ): super().__init__(**SCREAMING_SNAKE_CASE__) lowercase__ : str = hidden_size lowercase__ : Union[str, Any] = intermediate_size lowercase__ : Optional[int] = projection_dim lowercase__ : Dict = num_hidden_layers lowercase__ : Dict = num_attention_heads lowercase__ : List[str] = patch_size lowercase__ : Optional[int] = image_size lowercase__ : Optional[int] = initializer_range lowercase__ : Any = attention_dropout lowercase__ : Tuple = layer_norm_eps lowercase__ : str = hidden_act @classmethod def snake_case_ ( cls , a , **a): cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__) lowercase__ , lowercase__ : Tuple = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) # get the vision config dict if we are loading from BlipConfig if config_dict.get('model_type') == "blip": lowercase__ : Union[str, Any] = 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(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__) class SCREAMING_SNAKE_CASE__ (UpperCamelCase__ ): __lowerCamelCase : Dict = """blip""" __lowerCamelCase : Optional[Any] = True def __init__( self , a=None , a=None , a=512 , a=2.6_592 , a=256 , **a , ): super().__init__(**SCREAMING_SNAKE_CASE__) if text_config is None: lowercase__ : int = {} logger.info('`text_config` is `None`. Initializing the `BlipTextConfig` with default values.') if vision_config is None: lowercase__ : int = {} logger.info('`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.') lowercase__ : Dict = BlipTextConfig(**SCREAMING_SNAKE_CASE__) lowercase__ : List[str] = BlipVisionConfig(**SCREAMING_SNAKE_CASE__) lowercase__ : Tuple = self.vision_config.hidden_size lowercase__ : str = projection_dim lowercase__ : Dict = logit_scale_init_value lowercase__ : int = 1.0 lowercase__ : int = 0.02 lowercase__ : Optional[Any] = image_text_hidden_size @classmethod def snake_case_ ( cls , a , a , **a): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE__) def snake_case_ ( self): lowercase__ : Union[str, Any] = copy.deepcopy(self.__dict__) lowercase__ : List[str] = self.text_config.to_dict() lowercase__ : Optional[Any] = self.vision_config.to_dict() lowercase__ : Optional[int] = self.__class__.model_type return output
164
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
"""simple docstring""" from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): def __init__( self : Dict , lowerCAmelCase : Optional[NestedDataStructureLike[PathLike]] = None , lowerCAmelCase : Optional[NamedSplit] = None , lowerCAmelCase : Optional[Features] = None , lowerCAmelCase : str = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[int] = None , **lowerCAmelCase : int , ): lowerCAmelCase = path_or_paths lowerCAmelCase = split if split or isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else """train""" lowerCAmelCase = features lowerCAmelCase = cache_dir lowerCAmelCase = keep_in_memory lowerCAmelCase = streaming lowerCAmelCase = num_proc lowerCAmelCase = kwargs @abstractmethod def __lowercase ( self : int ): pass class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): def __init__( self : Dict , lowerCAmelCase : Optional[Features] = None , lowerCAmelCase : str = None , lowerCAmelCase : bool = False , lowerCAmelCase : bool = False , lowerCAmelCase : Optional[int] = None , **lowerCAmelCase : Optional[Any] , ): lowerCAmelCase = features lowerCAmelCase = cache_dir lowerCAmelCase = keep_in_memory lowerCAmelCase = streaming lowerCAmelCase = num_proc lowerCAmelCase = kwargs @abstractmethod def __lowercase ( self : Optional[int] ): pass
169
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0
import re import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class A__ ( UpperCamelCase__): _UpperCAmelCase : Optional[int] = ["""image_processor""", """tokenizer"""] _UpperCAmelCase : Any = """AutoImageProcessor""" _UpperCAmelCase : int = """AutoTokenizer""" def __init__( self , __magic_name__=None , __magic_name__=None , **__magic_name__ ): lowerCamelCase : List[Any] = None if "feature_extractor" in kwargs: warnings.warn( """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`""" """ instead.""" , SCREAMING_SNAKE_CASE__ , ) lowerCamelCase : Any = kwargs.pop("""feature_extractor""" ) lowerCamelCase : List[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("""You need to specify an `image_processor`.""" ) if tokenizer is None: raise ValueError("""You need to specify a `tokenizer`.""" ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Dict = self.image_processor lowerCamelCase : List[Any] = False def __call__( self , *__magic_name__ , **__magic_name__ ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Union[str, Any] = kwargs.pop("""images""" , SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Union[str, Any] = kwargs.pop("""text""" , SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: lowerCamelCase : Dict = args[0] lowerCamelCase : int = args[1:] 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: lowerCamelCase : List[Any] = self.image_processor(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is not None: lowerCamelCase : Optional[Any] = self.tokenizer(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if text is None: return inputs elif images is None: return encodings else: lowerCamelCase : List[str] = encodings["""input_ids"""] return inputs def UpperCamelCase__ ( self , *__magic_name__ , **__magic_name__ ): return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( self , *__magic_name__ , **__magic_name__ ): return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) @contextmanager def UpperCamelCase__ ( self ): warnings.warn( """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """ """labels by using the argument `text` of the regular `__call__` method (either in the same call as """ """your images inputs, or in a separate call.""" ) lowerCamelCase : Optional[Any] = True lowerCamelCase : Tuple = self.tokenizer yield lowerCamelCase : int = self.image_processor lowerCamelCase : Optional[Any] = False def UpperCamelCase__ ( self , __magic_name__ , __magic_name__=False , __magic_name__=None ): if added_vocab is None: lowerCamelCase : Any = self.tokenizer.get_added_vocab() lowerCamelCase : Dict = {} while tokens: lowerCamelCase : Any = re.search(r"""<s_(.*?)>""" , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) if start_token is None: break lowerCamelCase : List[str] = start_token.group(1 ) lowerCamelCase : str = re.search(rF'''</s_{key}>''' , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) lowerCamelCase : Optional[Any] = start_token.group() if end_token is None: lowerCamelCase : Optional[Any] = tokens.replace(SCREAMING_SNAKE_CASE__ , """""" ) else: lowerCamelCase : Union[str, Any] = end_token.group() lowerCamelCase : List[Any] = re.escape(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Tuple = re.escape(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : str = re.search(F'''{start_token_escaped}(.*?){end_token_escaped}''' , SCREAMING_SNAKE_CASE__ , re.IGNORECASE ) if content is not None: lowerCamelCase : str = content.group(1 ).strip() if r"<s_" in content and r"</s_" in content: # non-leaf node lowerCamelCase : Optional[int] = self.tokenajson(SCREAMING_SNAKE_CASE__ , is_inner_value=SCREAMING_SNAKE_CASE__ , added_vocab=SCREAMING_SNAKE_CASE__ ) if value: if len(SCREAMING_SNAKE_CASE__ ) == 1: lowerCamelCase : Dict = value[0] lowerCamelCase : Dict = value else: # leaf nodes lowerCamelCase : List[Any] = [] for leaf in content.split(r"""<sep/>""" ): lowerCamelCase : Union[str, Any] = leaf.strip() if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>": lowerCamelCase : Optional[Any] = leaf[1:-2] # for categorical special tokens output[key].append(SCREAMING_SNAKE_CASE__ ) if len(output[key] ) == 1: lowerCamelCase : Any = output[key][0] lowerCamelCase : Optional[int] = tokens[tokens.find(SCREAMING_SNAKE_CASE__ ) + len(SCREAMING_SNAKE_CASE__ ) :].strip() if tokens[:6] == r"<sep/>": # non-leaf nodes return [output] + self.tokenajson(tokens[6:] , is_inner_value=SCREAMING_SNAKE_CASE__ , added_vocab=SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ): return [output] if is_inner_value else output else: return [] if is_inner_value else {"text_sequence": tokens} @property def UpperCamelCase__ ( self ): warnings.warn( """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , SCREAMING_SNAKE_CASE__ , ) return self.image_processor_class @property def UpperCamelCase__ ( self ): warnings.warn( """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , SCREAMING_SNAKE_CASE__ , ) return self.image_processor
681
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
0
'''simple docstring''' class A_ : """simple docstring""" def __init__( self :int , lowerCAmelCase__ :list ) -> None: '''simple docstring''' snake_case_ : Union[str, Any] = set_counts snake_case_ : Any = max(SCREAMING_SNAKE_CASE__ ) snake_case_ : List[str] = len(SCREAMING_SNAKE_CASE__ ) snake_case_ : List[Any] = [1] * num_sets snake_case_ : Dict = list(range(SCREAMING_SNAKE_CASE__ ) ) def _A ( self :Optional[int] , lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> bool: '''simple docstring''' snake_case_ : List[str] = self.get_parent(SCREAMING_SNAKE_CASE__ ) snake_case_ : Dict = self.get_parent(SCREAMING_SNAKE_CASE__ ) 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_ : Optional[Any] = 0 snake_case_ : str = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 snake_case_ : Optional[int] = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] snake_case_ : Any = 0 snake_case_ : Tuple = src_parent snake_case_ : Dict = self.set_counts[src_parent] snake_case_ : str = max(self.max_set , SCREAMING_SNAKE_CASE__ ) return True def _A ( self :Optional[int] , lowerCAmelCase__ :int ) -> int: '''simple docstring''' if self.parents[disj_set] == disj_set: return disj_set snake_case_ : Dict = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
653
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
0
'''simple docstring''' import argparse import json import logging import os import sys from unittest.mock import patch from transformers.testing_utils import TestCasePlus, get_gpu_count, slow _SCREAMING_SNAKE_CASE = [ os.path.join(os.path.dirname(__file__), dirname) for dirname in [ "text-classification", "language-modeling", "summarization", "token-classification", "question-answering", ] ] sys.path.extend(SRC_DIRS) if SRC_DIRS is not None: import run_clm_flax import run_flax_glue import run_flax_ner import run_mlm_flax import run_qa import run_summarization_flax import run_ta_mlm_flax logging.basicConfig(level=logging.DEBUG) _SCREAMING_SNAKE_CASE = logging.getLogger() def __a(): '''simple docstring''' _lowerCAmelCase = argparse.ArgumentParser() parser.add_argument("-f" ) _lowerCAmelCase = parser.parse_args() return args.f def __a(SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : Any="eval" ): '''simple docstring''' _lowerCAmelCase = os.path.join(lowerCAmelCase_ , F'''{split}_results.json''' ) if os.path.exists(lowerCAmelCase_ ): with open(lowerCAmelCase_ , "r" ) as f: return json.load(lowerCAmelCase_ ) raise ValueError(F'''can\'t find {path}''' ) _SCREAMING_SNAKE_CASE = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class lowerCAmelCase_ ( UpperCamelCase__ ): def _snake_case ( self ) -> Tuple: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --eval_steps=2\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_flax_glue.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) @slow def _snake_case ( self ) -> str: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_clm_flax.py\n --model_name_or_path distilgpt2\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --block_size 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_clm_flax.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertLess(result["eval_perplexity"] , 100 ) @slow def _snake_case ( self ) -> Union[str, Any]: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_summarization.py\n --model_name_or_path t5-small\n --train_file tests/fixtures/tests_samples/xsum/sample.json\n --validation_file tests/fixtures/tests_samples/xsum/sample.json\n --test_file tests/fixtures/tests_samples/xsum/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=8\n --do_train\n --do_eval\n --do_predict\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --predict_with_generate\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_summarization_flax.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ , split="test" ) self.assertGreaterEqual(result["test_rouge1"] , 10 ) self.assertGreaterEqual(result["test_rouge2"] , 2 ) self.assertGreaterEqual(result["test_rougeL"] , 7 ) self.assertGreaterEqual(result["test_rougeLsum"] , 7 ) @slow def _snake_case ( self ) -> str: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_mlm.py\n --model_name_or_path distilroberta-base\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --logging_steps 2 --eval_steps 2\n --do_train\n --do_eval\n --num_train_epochs=1\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_mlm_flax.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertLess(result["eval_perplexity"] , 42 ) @slow def _snake_case ( self ) -> Optional[int]: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_t5_mlm_flax.py\n --model_name_or_path t5-small\n --train_file ./tests/fixtures/sample_text.txt\n --validation_file ./tests/fixtures/sample_text.txt\n --do_train\n --do_eval\n --max_seq_length 128\n --per_device_train_batch_size 4\n --per_device_eval_batch_size 4\n --num_train_epochs 2\n --logging_steps 2 --eval_steps 2\n --output_dir {tmp_dir}\n --overwrite_output_dir\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_ta_mlm_flax.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(result["eval_accuracy"] , 0.42 ) @slow def _snake_case ( self ) -> Optional[Any]: # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu _lowerCAmelCase = 7 if get_gpu_count() > 1 else 2 _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_flax_ner.py\n --model_name_or_path bert-base-uncased\n --train_file tests/fixtures/tests_samples/conll/sample.json\n --validation_file tests/fixtures/tests_samples/conll/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --do_train\n --do_eval\n --warmup_steps=2\n --learning_rate=2e-4\n --logging_steps 2 --eval_steps 2\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=2\n --num_train_epochs={epochs}\n --seed 7\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_flax_ner.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertGreaterEqual(result["eval_f1"] , 0.3 ) @slow def _snake_case ( self ) -> Tuple: _lowerCAmelCase = self.get_auto_remove_tmp_dir() _lowerCAmelCase = f'''\n run_qa.py\n --model_name_or_path bert-base-uncased\n --version_2_with_negative\n --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --num_train_epochs=3\n --warmup_steps=2\n --do_train\n --do_eval\n --logging_steps 2 --eval_steps 2\n --learning_rate=2e-4\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n '''.split() with patch.object(SCREAMING_SNAKE_CASE__ , "argv" , SCREAMING_SNAKE_CASE__ ): run_qa.main() _lowerCAmelCase = get_results(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(result["eval_f1"] , 30 ) self.assertGreaterEqual(result["eval_exact"] , 30 )
18
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
0
"""simple docstring""" import argparse import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_dummies.py SCREAMING_SNAKE_CASE__ : int ='src/diffusers' # Matches is_xxx_available() SCREAMING_SNAKE_CASE__ : List[Any] =re.compile(R'is\_([a-z_]*)_available\(\)') # Matches from xxx import bla SCREAMING_SNAKE_CASE__ : Tuple =re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') SCREAMING_SNAKE_CASE__ : Any ='\n{0} = None\n' SCREAMING_SNAKE_CASE__ : str ='\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n\n @classmethod\n def from_config(cls, *args, **kwargs):\n requires_backends(cls, {1})\n\n @classmethod\n def from_pretrained(cls, *args, **kwargs):\n requires_backends(cls, {1})\n' SCREAMING_SNAKE_CASE__ : Dict ='\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n' def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->int: _lowerCamelCase : Tuple = _re_backend.findall(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) == 0: return None return "_and_".join(lowerCAmelCase_ ) def UpperCamelCase ( ) ->Optional[Any]: with open(os.path.join(lowerCAmelCase_ , '''__init__.py''' ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: _lowerCamelCase : str = f.readlines() # Get to the point we do the actual imports for type checking _lowerCamelCase : int = 0 _lowerCamelCase : Dict = {} # Go through the end of the file while line_index < len(lowerCAmelCase_ ): # If the line contains is_backend_available, we grab all objects associated with the `else` block _lowerCamelCase : Optional[int] = find_backend(lines[line_index] ) if backend is not None: while not lines[line_index].startswith('''else:''' ): line_index += 1 line_index += 1 _lowerCamelCase : Optional[Any] = [] # Until we unindent, add backend objects to the list while line_index < len(lowerCAmelCase_ ) and len(lines[line_index] ) > 1: _lowerCamelCase : Optional[int] = lines[line_index] _lowerCamelCase : Union[str, Any] = _re_single_line_import.search(lowerCAmelCase_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 if len(lowerCAmelCase_ ) > 0: _lowerCamelCase : Union[str, Any] = objects else: line_index += 1 return backend_specific_objects def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Any: if name.isupper(): return DUMMY_CONSTANT.format(lowerCAmelCase_ ) elif name.islower(): return DUMMY_FUNCTION.format(lowerCAmelCase_ , lowerCAmelCase_ ) else: return DUMMY_CLASS.format(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCamelCase ( SCREAMING_SNAKE_CASE_=None ) ->int: if backend_specific_objects is None: _lowerCamelCase : List[Any] = read_init() # For special correspondence backend to module name as used in the function requires_modulename _lowerCamelCase : Union[str, Any] = {} for backend, objects in backend_specific_objects.items(): _lowerCamelCase : Optional[Any] = '''[''' + ''', '''.join(F'''"{b}"''' for b in backend.split('''_and_''' ) ) + ''']''' _lowerCamelCase : Optional[int] = '''# This file is autogenerated by the command `make fix-copies`, do not edit.\n''' dummy_file += "from ..utils import DummyObject, requires_backends\n\n" dummy_file += "\n".join([create_dummy_object(lowerCAmelCase_ , lowerCAmelCase_ ) for o in objects] ) _lowerCamelCase : int = dummy_file return dummy_files def UpperCamelCase ( SCREAMING_SNAKE_CASE_=False ) ->str: _lowerCamelCase : Any = create_dummy_files() # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py _lowerCamelCase : Dict = {'''torch''': '''pt'''} # Locate actual dummy modules and read their content. _lowerCamelCase : List[str] = os.path.join(lowerCAmelCase_ , '''utils''' ) _lowerCamelCase : Union[str, Any] = { backend: os.path.join(lowerCAmelCase_ , F'''dummy_{short_names.get(lowerCAmelCase_ , lowerCAmelCase_ )}_objects.py''' ) for backend in dummy_files.keys() } _lowerCamelCase : int = {} for backend, file_path in dummy_file_paths.items(): if os.path.isfile(lowerCAmelCase_ ): with open(lowerCAmelCase_ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: _lowerCamelCase : List[Any] = f.read() else: _lowerCamelCase : List[str] = '''''' for backend in dummy_files.keys(): if dummy_files[backend] != actual_dummies[backend]: if overwrite: print( F'''Updating diffusers.utils.dummy_{short_names.get(lowerCAmelCase_ , lowerCAmelCase_ )}_objects.py as the main ''' '''__init__ has new objects.''' ) with open(dummy_file_paths[backend] , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(dummy_files[backend] ) else: raise ValueError( '''The main __init__ has objects that are not present in ''' F'''diffusers.utils.dummy_{short_names.get(lowerCAmelCase_ , lowerCAmelCase_ )}_objects.py. Run `make fix-copies` ''' '''to fix this.''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int =argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') SCREAMING_SNAKE_CASE__ : int =parser.parse_args() check_dummies(args.fix_and_overwrite)
434
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup _snake_case = '''https://www.indeed.co.in/jobs?q=mobile+app+development&l=''' def __snake_case ( SCREAMING_SNAKE_CASE: str = "mumbai" ): """simple docstring""" _lowerCAmelCase = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): _lowerCAmelCase = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() _lowerCAmelCase = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('''Bangalore'''), 1): print(f'Job {i:>2} is {job[0]} at {job[1]}')
580
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = ["pixel_values"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 255 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = size if size is not None else {"shortest_edge": 384} lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = do_resize lowerCAmelCase__ = size # Default value set here for backwards compatibility where the value in config is None lowerCAmelCase__ = crop_pct if crop_pct is not None else 224 / 256 lowerCAmelCase__ = resample lowerCAmelCase__ = do_rescale lowerCAmelCase__ = rescale_factor lowerCAmelCase__ = do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCAmelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : int , ) -> np.ndarray: lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}' ) lowerCAmelCase__ = size["shortest_edge"] if shortest_edge < 384: # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct lowerCAmelCase__ = int(shortest_edge / crop_pct ) lowerCAmelCase__ = get_resize_output_image_size(SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # then crop to (shortest_edge, shortest_edge) return center_crop(image=SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # warping (no cropping) when evaluated at 384 or larger return resize( SCREAMING_SNAKE_CASE__ , size=(shortest_edge, shortest_edge) , resample=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[int, float] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> List[Any]: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : float = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : ChannelDimension = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Dict , ) -> PIL.Image.Image: lowerCAmelCase__ = do_resize if do_resize is not None else self.do_resize lowerCAmelCase__ = crop_pct if crop_pct is not None else self.crop_pct lowerCAmelCase__ = resample if resample is not None else self.resample lowerCAmelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCAmelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCAmelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCAmelCase__ = image_mean if image_mean is not None else self.image_mean lowerCAmelCase__ = image_std if image_std is not None else self.image_std lowerCAmelCase__ = size if size is not None else self.size lowerCAmelCase__ = get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_resize and size["shortest_edge"] < 384 and crop_pct is None: raise ValueError("crop_pct must be specified if size < 384." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. lowerCAmelCase__ = [to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: lowerCAmelCase__ = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , crop_pct=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: lowerCAmelCase__ = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: lowerCAmelCase__ = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] lowerCAmelCase__ = {"pixel_values": images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ )
61
0
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def UpperCamelCase ( __lowercase : Tuple=None ,__lowercase : Any=None ): '''simple docstring''' return field(default_factory=lambda: default ,metadata=lowerCAmelCase_ ) @dataclass class UpperCAmelCase : '''simple docstring''' lowerCamelCase_ = field( metadata={'''help''': '''The csv file to plot.'''} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={ '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.''' } , ) lowerCamelCase_ = field( default=UpperCamelCase__ , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , ) lowerCamelCase_ = list_field( default=UpperCamelCase__ , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} ) def UpperCamelCase ( __lowercase : Optional[int] ): '''simple docstring''' try: int(lowerCAmelCase_ ) return True except ValueError: return False def UpperCamelCase ( __lowercase : Optional[int] ): '''simple docstring''' try: float(lowerCAmelCase_ ) return True except ValueError: return False class UpperCAmelCase : '''simple docstring''' def __init__( self , lowercase ): """simple docstring""" A_ : Optional[int] = args A_ : Tuple = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}} ) with open(self.args.csv_file , newline='' ) as csv_file: A_ : Tuple = csv.DictReader(SCREAMING_SNAKE_CASE__ ) for row in reader: A_ : str = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'] ) ) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'] ) ) if can_convert_to_int(row['result'] ): # value is not None A_ : Optional[int] = int(row['result'] ) elif can_convert_to_float(row['result'] ): # value is not None A_ : List[str] = float(row['result'] ) def lowerCAmelCase_ ( self ): """simple docstring""" A_ , A_ : List[str] = plt.subplots() A_ : Optional[int] = 'Time usage' if self.args.is_time else 'Memory usage' A_ : Tuple = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log' ) ax.set_yscale('log' ) for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter() ) for model_name_idx, model_name in enumerate(self.result_dict.keys() ): A_ : Optional[int] = sorted(set(self.result_dict[model_name]['bsz'] ) ) A_ : List[Any] = sorted(set(self.result_dict[model_name]['seq_len'] ) ) A_ : Dict = self.result_dict[model_name]['result'] ((A_) , (A_)) : List[str] = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) A_ : Union[str, Any] = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: A_ : Any = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] , dtype=SCREAMING_SNAKE_CASE__ , ) else: A_ : Tuple = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] , dtype=np.floataa , ) ((A_) , (A_)) : Tuple = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) A_ : Union[str, Any] = np.asarray(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[: len(SCREAMING_SNAKE_CASE__ )] plt.scatter( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , label=F'''{label_model_name} - {inner_loop_label}: {inner_loop_value}''' ) plt.plot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '--' ) title_str += F''' {label_model_name} vs.''' A_ : str = title_str[:-4] A_ : List[str] = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(SCREAMING_SNAKE_CASE__ ) plt.xlabel(SCREAMING_SNAKE_CASE__ ) plt.ylabel(SCREAMING_SNAKE_CASE__ ) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file ) else: plt.show() def UpperCamelCase ( ): '''simple docstring''' A_ : Dict = HfArgumentParser(lowerCAmelCase_ ) A_ : str = parser.parse_args_into_dataclasses()[0] A_ : Optional[Any] = Plot(args=lowerCAmelCase_ ) plot.plot() if __name__ == "__main__": main()
558
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 __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : Any ) -> int: lowerCAmelCase__ = "ZinengTang/tvlt-base" lowerCAmelCase__ = tempfile.mkdtemp() def a ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return TvltImageProcessor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: return TvltFeatureExtractor.from_pretrained(self.checkpoint , **SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def a ( self : Any ) -> Union[str, Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase__ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> List[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = feature_extractor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : Dict ) -> str: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="np" ) lowerCAmelCase__ = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a ( self : int ) -> Any: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.ones([12_000] ) lowerCAmelCase__ = np.ones([3, 224, 224] ) lowerCAmelCase__ = processor(audio=SCREAMING_SNAKE_CASE__ , images=SCREAMING_SNAKE_CASE__ ) 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(SCREAMING_SNAKE_CASE__ ): processor() def a ( self : Tuple ) -> Optional[Any]: lowerCAmelCase__ = self.get_image_processor() lowerCAmelCase__ = self.get_feature_extractor() lowerCAmelCase__ = TvltProcessor(image_processor=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ ) 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" , )
61
0
"""simple docstring""" import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class lowercase ( unittest.TestCase ,UpperCamelCase__ ): def UpperCAmelCase (self : Tuple ) -> List[Any]: """simple docstring""" lowerCAmelCase = load_tool('''text-to-speech''' ) self.tool.setup() def UpperCAmelCase (self : Dict ) -> Optional[int]: """simple docstring""" torch.manual_seed(0 ) lowerCAmelCase = self.tool('''hey''' ) lowerCAmelCase = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) ,) ) def UpperCAmelCase (self : List[Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) lowerCAmelCase = self.tool('''hey''' ) lowerCAmelCase = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0_00_59_66_66_88_32_11_58_29, -0.0_00_36_57_64_01_90_79_50_64, -0.00_01_34_39_50_27_99_88_34_85] ) ,) )
535
import os # Precomputes a list of the 100 first triangular numbers UpperCamelCase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def _A ( ): """simple docstring""" lowerCAmelCase__ = os.path.dirname(os.path.realpath(lowerCAmelCase_ ) ) lowerCAmelCase__ = os.path.join(lowerCAmelCase_ , "words.txt" ) lowerCAmelCase__ = "" with open(lowerCAmelCase_ ) as f: lowerCAmelCase__ = f.readline() lowerCAmelCase__ = [word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] lowerCAmelCase__ = [ word for word in [sum(ord(lowerCAmelCase_ ) - 64 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowerCAmelCase_ ) if __name__ == "__main__": print(solution())
61
0
from collections.abc import Callable def snake_case ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): '''simple docstring''' __lowercase = a __lowercase = b if function(lowerCAmelCase_ ) == 0: # one of the a or b is a root for the function return a elif function(lowerCAmelCase_ ) == 0: return b elif ( function(lowerCAmelCase_ ) * function(lowerCAmelCase_ ) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("""could not find root in given interval.""" ) else: __lowercase = start + (end - start) / 2.0 while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7 if function(lowerCAmelCase_ ) == 0: return mid elif function(lowerCAmelCase_ ) * function(lowerCAmelCase_ ) < 0: __lowercase = mid else: __lowercase = mid __lowercase = start + (end - start) / 2.0 return mid def snake_case ( lowerCamelCase ): '''simple docstring''' return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
80
import random def _A ( lowerCAmelCase_ : Dict , lowerCAmelCase_ : int , lowerCAmelCase_ : Any ): """simple docstring""" lowerCAmelCase__ = a[left_index] lowerCAmelCase__ = left_index + 1 for j in range(left_index + 1 , lowerCAmelCase_ ): if a[j] < pivot: lowerCAmelCase__ , lowerCAmelCase__ = a[i], a[j] i += 1 lowerCAmelCase__ , lowerCAmelCase__ = a[i - 1], a[left_index] return i - 1 def _A ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str ): """simple docstring""" if left < right: lowerCAmelCase__ = random.randint(lowerCAmelCase_ , right - 1 ) lowerCAmelCase__ , lowerCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound lowerCAmelCase__ = partition(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) quick_sort_random( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # recursive quicksort to the left of the pivot point quick_sort_random( lowerCAmelCase_ , pivot_index + 1 , lowerCAmelCase_ ) # recursive quicksort to the right of the pivot point def _A ( ): """simple docstring""" lowerCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() lowerCAmelCase__ = [int(lowerCAmelCase_ ) for item in user_input.split("," )] quick_sort_random(lowerCAmelCase_ , 0 , len(lowerCAmelCase_ ) ) print(lowerCAmelCase_ ) if __name__ == "__main__": main()
61
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCAmelCase_ : Optional[Any] = logging.getLogger(__name__) @dataclass class UpperCAmelCase__ : lowerCAmelCase_ = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) lowerCAmelCase_ = field( default=UpperCamelCase__ , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) lowerCAmelCase_ = field( default='NER' , metadata={'help': 'Task type to fine tune in training (e.g. NER, POS, etc)'} ) lowerCAmelCase_ = field( default=UpperCamelCase__ , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) lowerCAmelCase_ = field(default=UpperCamelCase__ , metadata={'help': 'Set this flag to use fast tokenization.'} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. lowerCAmelCase_ = field( default=UpperCamelCase__ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) @dataclass class UpperCAmelCase__ : lowerCAmelCase_ = field( metadata={'help': 'The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task.'} ) lowerCAmelCase_ = field( default=UpperCamelCase__ , metadata={'help': 'Path to a file containing all labels. If not specified, CoNLL-2003 labels are used.'} , ) lowerCAmelCase_ = field( default=128 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) lowerCAmelCase_ = field( default=UpperCamelCase__ , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) def A_ ( ): """simple docstring""" _lowerCamelCase : List[Any] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Tuple = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) _lowerCamelCase : str = import_module("tasks" ) try: _lowerCamelCase : Union[str, Any] = getattr(lowerCAmelCase_ , model_args.task_type ) _lowerCamelCase : int = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task _lowerCamelCase : str = token_classification_task.get_labels(data_args.labels ) _lowerCamelCase : Dict = dict(enumerate(lowerCAmelCase_ ) ) _lowerCamelCase : str = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _lowerCamelCase : Union[str, Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) _lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) _lowerCamelCase : Tuple = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets _lowerCamelCase : Any = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) _lowerCamelCase : Tuple = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(_lowerCAmelCase : np.ndarray , _lowerCAmelCase : np.ndarray ) -> Tuple[List[int], List[int]]: _lowerCamelCase : Tuple = np.argmax(lowerCAmelCase_ , axis=2 ) _lowerCamelCase , _lowerCamelCase : int = preds.shape _lowerCamelCase : str = [[] for _ in range(lowerCAmelCase_ )] _lowerCamelCase : List[Any] = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_lowerCAmelCase : EvalPrediction ) -> Dict: _lowerCamelCase , _lowerCamelCase : Dict = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator _lowerCamelCase : Dict = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer _lowerCamelCase : Any = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation _lowerCamelCase : Any = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) _lowerCamelCase : List[Any] = trainer.evaluate() _lowerCamelCase : List[Any] = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: _lowerCamelCase : int = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Any = trainer.predict(lowerCAmelCase_ ) _lowerCamelCase , _lowerCamelCase : str = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) _lowerCamelCase : int = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions _lowerCamelCase : int = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def A_ ( _lowerCAmelCase : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
44
import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process UpperCamelCase = logging.getLogger(__name__) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) snake_case__ = field( default="NER" , metadata={"help": "Task type to fine tune in training (e.g. NER, POS, etc)"} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) snake_case__ = field(default=UpperCamelCase__ , metadata={"help": "Set this flag to use fast tokenization."} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) @dataclass class __lowerCamelCase : """simple docstring""" snake_case__ = field( metadata={"help": "The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."} ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."} , ) snake_case__ = field( default=1_2_8 , metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) } , ) snake_case__ = field( default=UpperCamelCase__ , metadata={"help": "Overwrite the cached training and evaluation sets"} ) def _A ( ): """simple docstring""" lowerCAmelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. Use' " --overwrite_output_dir to overcome." ) lowerCAmelCase__ = import_module("tasks" ) try: lowerCAmelCase__ = getattr(lowerCAmelCase_ , model_args.task_type ) lowerCAmelCase__ = token_classification_task_clazz() except AttributeError: raise ValueError( F'Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. ' F'Available tasks classes are: {TokenClassificationTask.__subclasses__()}' ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" , lowerCAmelCase_ ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task lowerCAmelCase__ = token_classification_task.get_labels(data_args.labels ) lowerCAmelCase__ = dict(enumerate(lowerCAmelCase_ ) ) lowerCAmelCase__ = len(lowerCAmelCase_ ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCAmelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCAmelCase_ , idalabel=lowerCAmelCase_ , labelaid={label: i for i, label in enumerate(lowerCAmelCase_ )} , cache_dir=model_args.cache_dir , ) lowerCAmelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) lowerCAmelCase__ = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=lowerCAmelCase_ , cache_dir=model_args.cache_dir , ) # Get datasets lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) lowerCAmelCase__ = ( TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(lowerCAmelCase_ : np.ndarray , lowerCAmelCase_ : np.ndarray ) -> Tuple[List[int], List[int]]: lowerCAmelCase__ = np.argmax(lowerCAmelCase_ , axis=2 ) lowerCAmelCase__ , lowerCAmelCase__ = preds.shape lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] lowerCAmelCase__ = [[] for _ in range(lowerCAmelCase_ )] for i in range(lowerCAmelCase_ ): for j in range(lowerCAmelCase_ ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(lowerCAmelCase_ : EvalPrediction ) -> Dict: lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(lowerCAmelCase_ , lowerCAmelCase_ ), "precision": precision_score(lowerCAmelCase_ , lowerCAmelCase_ ), "recall": recall_score(lowerCAmelCase_ , lowerCAmelCase_ ), "f1": fa_score(lowerCAmelCase_ , lowerCAmelCase_ ), } # Data collator lowerCAmelCase__ = DataCollatorWithPadding(lowerCAmelCase_ , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer lowerCAmelCase__ = Trainer( model=lowerCAmelCase_ , args=lowerCAmelCase_ , train_dataset=lowerCAmelCase_ , eval_dataset=lowerCAmelCase_ , compute_metrics=lowerCAmelCase_ , data_collator=lowerCAmelCase_ , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation lowerCAmelCase__ = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCAmelCase__ = trainer.evaluate() lowerCAmelCase__ = os.path.join(training_args.output_dir , "eval_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: logger.info("***** Eval results *****" ) for key, value in result.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) results.update(lowerCAmelCase_ ) # Predict if training_args.do_predict: lowerCAmelCase__ = TokenClassificationDataset( token_classification_task=lowerCAmelCase_ , data_dir=data_args.data_dir , tokenizer=lowerCAmelCase_ , labels=lowerCAmelCase_ , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = trainer.predict(lowerCAmelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = align_predictions(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_results.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: for key, value in metrics.items(): logger.info(" %s = %s" , lowerCAmelCase_ , lowerCAmelCase_ ) writer.write("%s = %s\n" % (key, value) ) # Save predictions lowerCAmelCase__ = os.path.join(training_args.output_dir , "test_predictions.txt" ) if trainer.is_world_process_zero(): with open(lowerCAmelCase_ , "w" ) as writer: with open(os.path.join(data_args.data_dir , "test.txt" ) , "r" ) as f: token_classification_task.write_predictions_to_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) return results def _A ( lowerCAmelCase_ : Tuple ): """simple docstring""" main() if __name__ == "__main__": main()
61
0
import unittest import torch from diffusers import VQModel from diffusers.utils import floats_tensor, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE__ (UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): __lowerCamelCase : Dict = VQModel __lowerCamelCase : List[str] = """sample""" @property def snake_case_ ( self , a=(32, 32)): lowercase__ : Optional[int] = 4 lowercase__ : Optional[Any] = 3 lowercase__ : Optional[Any] = floats_tensor((batch_size, num_channels) + sizes).to(SCREAMING_SNAKE_CASE__) return {"sample": image} @property def snake_case_ ( self): return (3, 32, 32) @property def snake_case_ ( self): return (3, 32, 32) def snake_case_ ( self): lowercase__ : Optional[int] = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } lowercase__ : Union[str, Any] = self.dummy_input return init_dict, inputs_dict def snake_case_ ( self): pass def snake_case_ ( self): pass def snake_case_ ( self): lowercase__ , lowercase__ : Union[str, Any] = VQModel.from_pretrained('fusing/vqgan-dummy' , output_loading_info=SCREAMING_SNAKE_CASE__) self.assertIsNotNone(SCREAMING_SNAKE_CASE__) self.assertEqual(len(loading_info['missing_keys']) , 0) model.to(SCREAMING_SNAKE_CASE__) lowercase__ : Union[str, Any] = model(**self.dummy_input) assert image is not None, "Make sure output is not None" def snake_case_ ( self): lowercase__ : List[str] = VQModel.from_pretrained('fusing/vqgan-dummy') model.to(SCREAMING_SNAKE_CASE__).eval() torch.manual_seed(0) if torch.cuda.is_available(): torch.cuda.manual_seed_all(0) lowercase__ : Union[str, Any] = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size) lowercase__ : List[Any] = image.to(SCREAMING_SNAKE_CASE__) with torch.no_grad(): lowercase__ : Dict = model(SCREAMING_SNAKE_CASE__).sample lowercase__ : Optional[int] = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off lowercase__ : List[str] = torch.tensor([-0.0_153, -0.4_044, -0.1_880, -0.5_161, -0.2_418, -0.4_072, -0.1_612, -0.0_633, -0.0_143]) # fmt: on self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3))
164
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'spiece.model'} UpperCamelCase = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } UpperCamelCase = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ = ["input_ids", "attention_mask"] snake_case__ = [] def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str]="<unk>" , SCREAMING_SNAKE_CASE__ : List[str]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="<pad>" , SCREAMING_SNAKE_CASE__ : Any="[SEP]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[MASK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> None: lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowerCAmelCase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : List[str] ) -> List[str]: return self.sp_model.get_piece_size() def a ( self : List[str] ) -> Dict: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ) -> Any: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: lowerCAmelCase__ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowerCAmelCase__ = {} lowerCAmelCase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: lowerCAmelCase__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: lowerCAmelCase__ = [] lowerCAmelCase__ = "" lowerCAmelCase__ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token lowerCAmelCase__ = True lowerCAmelCase__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : bool = True , **SCREAMING_SNAKE_CASE__ : int , ) -> str: lowerCAmelCase__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowerCAmelCase__ = [] lowerCAmelCase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: lowerCAmelCase__ = re.sub(r" (\[(MASK|SEP)\])" , r"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: lowerCAmelCase__ = "".join(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowerCAmelCase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: lowerCAmelCase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] lowerCAmelCase__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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]
61
0
"""simple docstring""" from functools import lru_cache @lru_cache def lowercase (snake_case__ : int ) -> Any: '''simple docstring''' if num < 0: raise ValueError("""Number should not be negative.""" ) return 1 if num in (0, 1) else num * factorial(num - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
169
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "vit_msn" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=768 , SCREAMING_SNAKE_CASE__ : Optional[Any]=12 , SCREAMING_SNAKE_CASE__ : List[str]=12 , SCREAMING_SNAKE_CASE__ : Dict=3_072 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : List[str]=1e-0_6 , SCREAMING_SNAKE_CASE__ : Dict=224 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Dict=True , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = initializer_range lowerCAmelCase__ = layer_norm_eps lowerCAmelCase__ = image_size lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = qkv_bias
61
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel _lowerCamelCase ={ """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } _lowerCamelCase =AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def _a ( lowerCamelCase, lowerCamelCase=False ): lowerCamelCase , lowerCamelCase : Union[str, Any] = create_model( """HTSAT-tiny""", """roberta""", lowerCAmelCase_, precision="""fp32""", device="""cuda:0""" if torch.cuda.is_available() else """cpu""", enable_fusion=lowerCAmelCase_, fusion_type="""aff_2d""" if enable_fusion else None, ) return model, model_cfg def _a ( lowerCamelCase ): lowerCamelCase : str = {} lowerCamelCase : str = R""".*sequential.(\d+).*""" lowerCamelCase : Optional[int] = R""".*_projection.(\d+).*""" for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: lowerCamelCase : List[str] = key.replace(lowerCAmelCase_, lowerCAmelCase_ ) if re.match(lowerCAmelCase_, lowerCAmelCase_ ): # replace sequential layers with list lowerCamelCase : Dict = re.match(lowerCAmelCase_, lowerCAmelCase_ ).group(1 ) lowerCamelCase : Tuple = key.replace(F'''sequential.{sequential_layer}.''', F'''layers.{int(lowerCAmelCase_ )//3}.linear.''' ) elif re.match(lowerCAmelCase_, lowerCAmelCase_ ): lowerCamelCase : str = int(re.match(lowerCAmelCase_, lowerCAmelCase_ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... lowerCamelCase : int = 1 if projecton_layer == 0 else 2 lowerCamelCase : Optional[Any] = key.replace(F'''_projection.{projecton_layer}.''', F'''_projection.linear{transformers_projection_layer}.''' ) if "audio" and "qkv" in key: # split qkv into query key and value lowerCamelCase : Dict = value lowerCamelCase : List[str] = mixed_qkv.size(0 ) // 3 lowerCamelCase : Optional[int] = mixed_qkv[:qkv_dim] lowerCamelCase : Dict = mixed_qkv[qkv_dim : qkv_dim * 2] lowerCamelCase : Optional[Any] = mixed_qkv[qkv_dim * 2 :] lowerCamelCase : Optional[Any] = query_layer lowerCamelCase : Any = key_layer lowerCamelCase : Union[str, Any] = value_layer else: lowerCamelCase : List[str] = value return model_state_dict def _a ( lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=False ): lowerCamelCase , lowerCamelCase : List[str] = init_clap(lowerCAmelCase_, enable_fusion=lowerCAmelCase_ ) clap_model.eval() lowerCamelCase : Union[str, Any] = clap_model.state_dict() lowerCamelCase : str = rename_state_dict(lowerCAmelCase_ ) lowerCamelCase : int = ClapConfig() lowerCamelCase : Optional[Any] = enable_fusion lowerCamelCase : int = ClapModel(lowerCAmelCase_ ) # ignore the spectrogram embedding layer model.load_state_dict(lowerCAmelCase_, strict=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) transformers_config.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": _lowerCamelCase =argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") _lowerCamelCase =parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
681
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor UpperCamelCase = logging.get_logger(__name__) class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
61
0
'''simple docstring''' from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase : str = {'''configuration_van''': ['''VAN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VanConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[str] = [ '''VAN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''VanForImageClassification''', '''VanModel''', '''VanPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_van import VAN_PRETRAINED_CONFIG_ARCHIVE_MAP, VanConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_van import ( VAN_PRETRAINED_MODEL_ARCHIVE_LIST, VanForImageClassification, VanModel, VanPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
653
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL from PIL import Image from ...utils import ( BaseOutput, OptionalDependencyNotAvailable, is_flax_available, is_k_diffusion_available, is_k_diffusion_version, is_onnx_available, is_torch_available, is_transformers_available, is_transformers_version, ) @dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipeline_cycle_diffusion import CycleDiffusionPipeline from .pipeline_stable_diffusion import StableDiffusionPipeline from .pipeline_stable_diffusion_attend_and_excite import StableDiffusionAttendAndExcitePipeline from .pipeline_stable_diffusion_imgaimg import StableDiffusionImgaImgPipeline from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy from .pipeline_stable_diffusion_instruct_pixapix import StableDiffusionInstructPixaPixPipeline from .pipeline_stable_diffusion_latent_upscale import StableDiffusionLatentUpscalePipeline from .pipeline_stable_diffusion_ldmad import StableDiffusionLDMaDPipeline from .pipeline_stable_diffusion_model_editing import StableDiffusionModelEditingPipeline from .pipeline_stable_diffusion_panorama import StableDiffusionPanoramaPipeline from .pipeline_stable_diffusion_paradigms import StableDiffusionParadigmsPipeline from .pipeline_stable_diffusion_sag import StableDiffusionSAGPipeline from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline from .pipeline_stable_unclip import StableUnCLIPPipeline from .pipeline_stable_unclip_imgaimg import StableUnCLIPImgaImgPipeline from .safety_checker import StableDiffusionSafetyChecker from .stable_unclip_image_normalizer import StableUnCLIPImageNormalizer try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline else: from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.26.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ( StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionPixaPixZeroPipeline, ) else: from .pipeline_stable_diffusion_depthaimg import StableDiffusionDepthaImgPipeline from .pipeline_stable_diffusion_diffedit import StableDiffusionDiffEditPipeline from .pipeline_stable_diffusion_pixapix_zero import StableDiffusionPixaPixZeroPipeline try: if not ( is_torch_available() and is_transformers_available() and is_k_diffusion_available() and is_k_diffusion_version('>=', '0.0.12') ): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline try: if not (is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_onnx_objects import * # noqa F403 else: from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline from .pipeline_onnx_stable_diffusion_imgaimg import OnnxStableDiffusionImgaImgPipeline from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy from .pipeline_onnx_stable_diffusion_upscale import OnnxStableDiffusionUpscalePipeline if is_transformers_available() and is_flax_available(): import flax @flax.struct.dataclass class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = 42 snake_case__ = 42 from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline from .pipeline_flax_stable_diffusion_imgaimg import FlaxStableDiffusionImgaImgPipeline from .pipeline_flax_stable_diffusion_inpaint import FlaxStableDiffusionInpaintPipeline from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
61
0
'''simple docstring''' def __a(SCREAMING_SNAKE_CASE_ : int = 1000 ): '''simple docstring''' return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) ) if __name__ == "__main__": print(solution())
18
def _A ( lowerCAmelCase_ : int ): """simple docstring""" if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" lowerCAmelCase__ = False if num < 0: lowerCAmelCase__ = True lowerCAmelCase__ = -num lowerCAmelCase__ = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) return "0b" + "".join(str(lowerCAmelCase_ ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
61
0
"""simple docstring""" from __future__ import annotations import math import random from typing import Any class _UpperCAmelCase : """simple docstring""" def __init__( self ) -> None: _lowerCamelCase : Optional[int] = [] _lowerCamelCase : Optional[Any] = 0 _lowerCamelCase : Optional[Any] = 0 def a__ ( self ) -> bool: return self.head == self.tail def a__ ( self , _lowercase ) -> None: self.data.append(SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : Optional[Any] = self.tail + 1 def a__ ( self ) -> Any: _lowerCamelCase : Optional[Any] = self.data[self.head] _lowerCamelCase : Optional[int] = self.head + 1 return ret def a__ ( self ) -> int: return self.tail - self.head def a__ ( self ) -> None: print(self.data ) print('''**************''' ) print(self.data[self.head : self.tail] ) class _UpperCAmelCase : """simple docstring""" def __init__( self , _lowercase ) -> None: _lowerCamelCase : Any = data _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : str = None _lowerCamelCase : Optional[int] = 1 def a__ ( self ) -> Any: return self.data def a__ ( self ) -> MyNode | None: return self.left def a__ ( self ) -> MyNode | None: return self.right def a__ ( self ) -> int: return self.height def a__ ( self , _lowercase ) -> None: _lowerCamelCase : str = data def a__ ( self , _lowercase ) -> None: _lowerCamelCase : Optional[Any] = node def a__ ( self , _lowercase ) -> None: _lowerCamelCase : Any = node def a__ ( self , _lowercase ) -> None: _lowerCamelCase : Optional[Any] = height def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Union[str, Any]: if node is None: return 0 return node.get_height() def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->List[str]: if a > b: return a return b def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Union[str, Any]: print('''left rotation node:''' , node.get_data() ) _lowerCamelCase : Tuple = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(lowerCAmelCase_ ) _lowerCamelCase : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) _lowerCamelCase : Dict = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase_ ) return ret def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->str: print('''right rotation node:''' , node.get_data() ) _lowerCamelCase : Dict = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(lowerCAmelCase_ ) _lowerCamelCase : Any = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) _lowerCamelCase : List[str] = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(lowerCAmelCase_ ) return ret def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->str: _lowerCamelCase : Tuple = node.get_left() assert left_child is not None node.set_left(left_rotation(lowerCAmelCase_ ) ) return right_rotation(lowerCAmelCase_ ) def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Optional[Any]: _lowerCamelCase : Any = node.get_right() assert right_child is not None node.set_right(right_rotation(lowerCAmelCase_ ) ) return left_rotation(lowerCAmelCase_ ) def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->List[Any]: if node is None: return MyNode(lowerCAmelCase_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , lowerCAmelCase_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected _lowerCamelCase : Any = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child _lowerCamelCase : Optional[int] = right_rotation(lowerCAmelCase_ ) else: _lowerCamelCase : Dict = lr_rotation(lowerCAmelCase_ ) else: node.set_right(insert_node(node.get_right() , lowerCAmelCase_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: _lowerCamelCase : int = node.get_right() assert right_child is not None if data < right_child.get_data(): _lowerCamelCase : Optional[int] = rl_rotation(lowerCAmelCase_ ) else: _lowerCamelCase : Tuple = left_rotation(lowerCAmelCase_ ) _lowerCamelCase : Optional[int] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(lowerCAmelCase_ ) return node def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Tuple: while True: _lowerCamelCase : List[str] = root.get_right() if right_child is None: break _lowerCamelCase : List[Any] = right_child return root.get_data() def UpperCamelCase ( SCREAMING_SNAKE_CASE_ ) ->Optional[int]: while True: _lowerCamelCase : Tuple = root.get_left() if left_child is None: break _lowerCamelCase : List[Any] = left_child return root.get_data() def UpperCamelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ->Optional[int]: _lowerCamelCase : Optional[Any] = root.get_left() _lowerCamelCase : int = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: _lowerCamelCase : Optional[int] = get_left_most(lowerCAmelCase_ ) root.set_data(lowerCAmelCase_ ) root.set_right(del_node(lowerCAmelCase_ , lowerCAmelCase_ ) ) elif left_child is not None: _lowerCamelCase : Tuple = left_child elif right_child is not None: _lowerCamelCase : Optional[Any] = right_child else: return None elif root.get_data() > data: if left_child is None: print('''No such data''' ) return root else: root.set_left(del_node(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(lowerCAmelCase_ , lowerCAmelCase_ ) ) if get_height(lowerCAmelCase_ ) - get_height(lowerCAmelCase_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): _lowerCamelCase : Union[str, Any] = left_rotation(lowerCAmelCase_ ) else: _lowerCamelCase : Any = rl_rotation(lowerCAmelCase_ ) elif get_height(lowerCAmelCase_ ) - get_height(lowerCAmelCase_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): _lowerCamelCase : Any = right_rotation(lowerCAmelCase_ ) else: _lowerCamelCase : str = lr_rotation(lowerCAmelCase_ ) _lowerCamelCase : List[Any] = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(lowerCAmelCase_ ) return root class _UpperCAmelCase : """simple docstring""" def __init__( self ) -> None: _lowerCamelCase : List[Any] = None def a__ ( self ) -> int: return get_height(self.root ) def a__ ( self , _lowercase ) -> None: print('''insert:''' + str(SCREAMING_SNAKE_CASE__ ) ) _lowerCamelCase : Dict = insert_node(self.root , SCREAMING_SNAKE_CASE__ ) def a__ ( self , _lowercase ) -> None: print('''delete:''' + str(SCREAMING_SNAKE_CASE__ ) ) if self.root is None: print('''Tree is empty!''' ) return _lowerCamelCase : Union[str, Any] = del_node(self.root , SCREAMING_SNAKE_CASE__ ) def __str__( self , ) -> str: # a level traversale, gives a more intuitive look on the tree _lowerCamelCase : Optional[int] = '''''' _lowerCamelCase : Optional[Any] = MyQueue() q.push(self.root ) _lowerCamelCase : Optional[int] = self.get_height() if layer == 0: return output _lowerCamelCase : Union[str, Any] = 0 while not q.is_empty(): _lowerCamelCase : Union[str, Any] = q.pop() _lowerCamelCase : List[str] = ''' ''' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(SCREAMING_SNAKE_CASE__ ) q.push(SCREAMING_SNAKE_CASE__ ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space _lowerCamelCase : Any = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , SCREAMING_SNAKE_CASE__ ) - 1: _lowerCamelCase : Optional[Any] = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def UpperCamelCase ( ) ->int: import doctest doctest.testmod() if __name__ == "__main__": _test() SCREAMING_SNAKE_CASE__ : Union[str, Any] =AVLtree() SCREAMING_SNAKE_CASE__ : Union[str, Any] =list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
434
from __future__ import annotations UpperCamelCase = '#' class __lowerCamelCase : """simple docstring""" def __init__( self : Dict ) -> None: lowerCAmelCase__ = {} def a ( self : Any , SCREAMING_SNAKE_CASE__ : str ) -> None: lowerCAmelCase__ = self._trie for char in text: if char not in trie: lowerCAmelCase__ = {} lowerCAmelCase__ = trie[char] lowerCAmelCase__ = True def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> tuple | list: lowerCAmelCase__ = self._trie for char in prefix: if char in trie: lowerCAmelCase__ = trie[char] else: return [] return self._elements(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : dict ) -> tuple: lowerCAmelCase__ = [] for c, v in d.items(): lowerCAmelCase__ = [" "] if c == END else [(c + s) for s in self._elements(SCREAMING_SNAKE_CASE__ )] result.extend(SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) UpperCamelCase = Trie() UpperCamelCase = ('depart', 'detergent', 'daring', 'dog', 'deer', 'deal') for word in words: trie.insert_word(word) def _A ( lowerCAmelCase_ : str ): """simple docstring""" lowerCAmelCase__ = trie.find_word(lowerCAmelCase_ ) return tuple(string + word for word in suffixes ) def _A ( ): """simple docstring""" print(autocomplete_using_trie("de" ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
61
0
"""simple docstring""" from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def __snake_case ( SCREAMING_SNAKE_CASE: List[str] ): """simple docstring""" if not is_accelerate_available(): return method _lowerCAmelCase = version.parse(accelerate.__version__ ).base_version if version.parse(lowerCAmelCase_ ) < version.parse('0.17.0' ): return method def wrapper(self: List[Any] , *SCREAMING_SNAKE_CASE: Dict , **SCREAMING_SNAKE_CASE: List[Any] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowerCAmelCase_ , **lowerCAmelCase_ ) return wrapper
580
import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class __lowerCamelCase : """simple docstring""" def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple=13 , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=3 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : Optional[int]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : List[Any]=37 , SCREAMING_SNAKE_CASE__ : int="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : Any=10 , SCREAMING_SNAKE_CASE__ : int=0.02 , SCREAMING_SNAKE_CASE__ : Tuple="divided_space_time" , SCREAMING_SNAKE_CASE__ : Optional[int]=None , ) -> List[str]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = image_size lowerCAmelCase__ = num_channels lowerCAmelCase__ = patch_size lowerCAmelCase__ = num_frames lowerCAmelCase__ = is_training lowerCAmelCase__ = use_labels lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = attention_type lowerCAmelCase__ = initializer_range lowerCAmelCase__ = scope lowerCAmelCase__ = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token lowerCAmelCase__ = (image_size // patch_size) ** 2 lowerCAmelCase__ = (num_frames) * self.num_patches_per_frame + 1 def a ( self : int ) -> Tuple: lowerCAmelCase__ = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase__ = None if self.use_labels: lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCAmelCase__ = self.get_config() return config, pixel_values, labels def a ( self : List[Any] ) -> Any: lowerCAmelCase__ = TimesformerConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , attention_type=self.attention_type , ) lowerCAmelCase__ = self.num_labels return config def a ( self : str , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: lowerCAmelCase__ = TimesformerModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: lowerCAmelCase__ = TimesformerForVideoClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ ) # verify the logits shape lowerCAmelCase__ = torch.Size((self.batch_size, self.num_labels) ) self.parent.assertEqual(result.logits.shape , SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () snake_case__ = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) snake_case__ = False snake_case__ = False snake_case__ = False snake_case__ = False def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = TimesformerModelTester(self ) lowerCAmelCase__ = ConfigTester( self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple=False ) -> str: lowerCAmelCase__ = copy.deepcopy(SCREAMING_SNAKE_CASE__ ) if return_labels: if model_class in get_values(SCREAMING_SNAKE_CASE__ ): lowerCAmelCase__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=SCREAMING_SNAKE_CASE__ ) return inputs_dict def a ( self : Optional[Any] ) -> List[str]: self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds" ) def a ( self : Union[str, Any] ) -> Tuple: pass def a ( self : Dict ) -> List[str]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase__ = [*signature.parameters.keys()] lowerCAmelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Optional[Any]: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] ) -> Tuple: lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*SCREAMING_SNAKE_CASE__ ) @slow def a ( self : str ) -> Tuple: for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase__ = TimesformerModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def a ( self : int ) -> Dict: if not self.has_attentions: pass else: lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase__ = True for model_class in self.all_model_classes: lowerCAmelCase__ = self.model_tester.seq_length lowerCAmelCase__ = self.model_tester.num_frames lowerCAmelCase__ = True lowerCAmelCase__ = False lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) lowerCAmelCase__ = len(SCREAMING_SNAKE_CASE__ ) # Check attention is always last and order is fine lowerCAmelCase__ = True lowerCAmelCase__ = True lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(out_len + 1 , len(SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , self.model_tester.num_hidden_layers ) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1] , ) def a ( self : List[str] ) -> Any: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] ): lowerCAmelCase__ = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowerCAmelCase__ = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowerCAmelCase__ = outputs.hidden_states lowerCAmelCase__ = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase__ , lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase__ = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): """simple docstring""" lowerCAmelCase__ = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video" , filename="eating_spaghetti.npy" , repo_type="dataset" ) lowerCAmelCase__ = np.load(lowerCAmelCase_ ) return list(lowerCAmelCase_ ) @require_torch @require_vision class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @cached_property def a ( self : Optional[Any] ) -> Union[str, Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def a ( self : Optional[Any] ) -> str: lowerCAmelCase__ = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400" ).to( SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.default_image_processor lowerCAmelCase__ = prepare_video() lowerCAmelCase__ = image_processor(video[:8] , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowerCAmelCase__ = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowerCAmelCase__ = torch.Size((1, 400) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = torch.tensor([-0.3_016, -0.7_713, -0.4_205] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
from ....configuration_utils import PretrainedConfig from ....utils import logging _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { """speechbrain/m-ctc-t-large""": """https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json""", # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class UpperCAmelCase ( UpperCamelCase__ ): '''simple docstring''' lowerCamelCase_ = '''mctct''' def __init__( self , lowercase=8_0_6_5 , lowercase=1_5_3_6 , lowercase=3_6 , lowercase=6_1_4_4 , lowercase=4 , lowercase=3_8_4 , lowercase=9_2_0 , lowercase=1E-5 , lowercase=0.3 , lowercase="relu" , lowercase=0.02 , lowercase=0.3 , lowercase=0.3 , lowercase=1 , lowercase=0 , lowercase=2 , lowercase=1 , lowercase=0.3 , lowercase=1 , lowercase=(7,) , lowercase=(3,) , lowercase=8_0 , lowercase=1 , lowercase=None , lowercase="sum" , lowercase=False , **lowercase , ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ , pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) A_ : Tuple = vocab_size A_ : Optional[Any] = hidden_size A_ : Dict = num_hidden_layers A_ : int = intermediate_size A_ : Dict = num_attention_heads A_ : Dict = attention_head_dim A_ : List[Any] = max_position_embeddings A_ : Any = layer_norm_eps A_ : int = layerdrop A_ : Union[str, Any] = hidden_act A_ : List[str] = initializer_range A_ : List[str] = hidden_dropout_prob A_ : Tuple = attention_probs_dropout_prob A_ : Optional[Any] = pad_token_id A_ : List[Any] = bos_token_id A_ : int = eos_token_id A_ : Any = conv_glu_dim A_ : Optional[Any] = conv_dropout A_ : Union[str, Any] = num_conv_layers A_ : Any = input_feat_per_channel A_ : Optional[Any] = input_channels A_ : str = conv_channels A_ : List[Any] = ctc_loss_reduction A_ : Optional[Any] = ctc_zero_infinity # prevents config testing fail with exporting to json A_ : int = list(SCREAMING_SNAKE_CASE__ ) A_ : int = list(SCREAMING_SNAKE_CASE__ ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( 'Configuration for convolutional module is incorrect. ' 'It is required that `len(config.conv_kernel)` == `config.num_conv_layers` ' F'''but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, ''' F'''`config.num_conv_layers = {self.num_conv_layers}`.''' )
558
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): """simple docstring""" lowerCAmelCase__ = ArgumentParser( description=( "PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowerCAmelCase_ , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowerCAmelCase_ , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowerCAmelCase_ ) return parser.parse_args() def _A ( ): """simple docstring""" lowerCAmelCase__ = parse_args() # Import training_script as a module. lowerCAmelCase__ = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) lowerCAmelCase__ = script_fpath.stem lowerCAmelCase__ = importlib.import_module(lowerCAmelCase_ ) # Patch sys.argv lowerCAmelCase__ = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
61
0
"""simple docstring""" from unittest.mock import Mock, patch from file_transfer.send_file import send_file @patch('''socket.socket''' ) @patch('''builtins.open''' ) def __magic_name__ ( _lowerCamelCase: Union[str, Any], _lowerCamelCase: Optional[int] ) -> List[Any]: '''simple docstring''' lowerCAmelCase = Mock() lowerCAmelCase = conn, Mock() lowerCAmelCase = iter([1, None] ) lowerCAmelCase = lambda _lowerCamelCase : next(lowerCAmelCase_ ) # ===== invoke ===== send_file(filename='''mytext.txt''', testing=lowerCAmelCase_ ) # ===== ensurance ===== sock.assert_called_once() sock.return_value.bind.assert_called_once() sock.return_value.listen.assert_called_once() sock.return_value.accept.assert_called_once() conn.recv.assert_called_once() file.return_value.__enter__.assert_called_once() file.return_value.__enter__.return_value.read.assert_called() conn.send.assert_called_once() conn.close.assert_called_once() sock.return_value.shutdown.assert_called_once() sock.return_value.close.assert_called_once()
535
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool UpperCamelCase = { 'Acehnese Arabic': 'ace_Arab', 'Acehnese Latin': 'ace_Latn', 'Mesopotamian Arabic': 'acm_Arab', 'Ta\'izzi-Adeni Arabic': 'acq_Arab', 'Tunisian Arabic': 'aeb_Arab', 'Afrikaans': 'afr_Latn', 'South Levantine Arabic': 'ajp_Arab', 'Akan': 'aka_Latn', 'Amharic': 'amh_Ethi', 'North Levantine Arabic': 'apc_Arab', 'Modern Standard Arabic': 'arb_Arab', 'Modern Standard Arabic Romanized': 'arb_Latn', 'Najdi Arabic': 'ars_Arab', 'Moroccan Arabic': 'ary_Arab', 'Egyptian Arabic': 'arz_Arab', 'Assamese': 'asm_Beng', 'Asturian': 'ast_Latn', 'Awadhi': 'awa_Deva', 'Central Aymara': 'ayr_Latn', 'South Azerbaijani': 'azb_Arab', 'North Azerbaijani': 'azj_Latn', 'Bashkir': 'bak_Cyrl', 'Bambara': 'bam_Latn', 'Balinese': 'ban_Latn', 'Belarusian': 'bel_Cyrl', 'Bemba': 'bem_Latn', 'Bengali': 'ben_Beng', 'Bhojpuri': 'bho_Deva', 'Banjar Arabic': 'bjn_Arab', 'Banjar Latin': 'bjn_Latn', 'Standard Tibetan': 'bod_Tibt', 'Bosnian': 'bos_Latn', 'Buginese': 'bug_Latn', 'Bulgarian': 'bul_Cyrl', 'Catalan': 'cat_Latn', 'Cebuano': 'ceb_Latn', 'Czech': 'ces_Latn', 'Chokwe': 'cjk_Latn', 'Central Kurdish': 'ckb_Arab', 'Crimean Tatar': 'crh_Latn', 'Welsh': 'cym_Latn', 'Danish': 'dan_Latn', 'German': 'deu_Latn', 'Southwestern Dinka': 'dik_Latn', 'Dyula': 'dyu_Latn', 'Dzongkha': 'dzo_Tibt', 'Greek': 'ell_Grek', 'English': 'eng_Latn', 'Esperanto': 'epo_Latn', 'Estonian': 'est_Latn', 'Basque': 'eus_Latn', 'Ewe': 'ewe_Latn', 'Faroese': 'fao_Latn', 'Fijian': 'fij_Latn', 'Finnish': 'fin_Latn', 'Fon': 'fon_Latn', 'French': 'fra_Latn', 'Friulian': 'fur_Latn', 'Nigerian Fulfulde': 'fuv_Latn', 'Scottish Gaelic': 'gla_Latn', 'Irish': 'gle_Latn', 'Galician': 'glg_Latn', 'Guarani': 'grn_Latn', 'Gujarati': 'guj_Gujr', 'Haitian Creole': 'hat_Latn', 'Hausa': 'hau_Latn', 'Hebrew': 'heb_Hebr', 'Hindi': 'hin_Deva', 'Chhattisgarhi': 'hne_Deva', 'Croatian': 'hrv_Latn', 'Hungarian': 'hun_Latn', 'Armenian': 'hye_Armn', 'Igbo': 'ibo_Latn', 'Ilocano': 'ilo_Latn', 'Indonesian': 'ind_Latn', 'Icelandic': 'isl_Latn', 'Italian': 'ita_Latn', 'Javanese': 'jav_Latn', 'Japanese': 'jpn_Jpan', 'Kabyle': 'kab_Latn', 'Jingpho': 'kac_Latn', 'Kamba': 'kam_Latn', 'Kannada': 'kan_Knda', 'Kashmiri Arabic': 'kas_Arab', 'Kashmiri Devanagari': 'kas_Deva', 'Georgian': 'kat_Geor', 'Central Kanuri Arabic': 'knc_Arab', 'Central Kanuri Latin': 'knc_Latn', 'Kazakh': 'kaz_Cyrl', 'Kabiyè': 'kbp_Latn', 'Kabuverdianu': 'kea_Latn', 'Khmer': 'khm_Khmr', 'Kikuyu': 'kik_Latn', 'Kinyarwanda': 'kin_Latn', 'Kyrgyz': 'kir_Cyrl', 'Kimbundu': 'kmb_Latn', 'Northern Kurdish': 'kmr_Latn', 'Kikongo': 'kon_Latn', 'Korean': 'kor_Hang', 'Lao': 'lao_Laoo', 'Ligurian': 'lij_Latn', 'Limburgish': 'lim_Latn', 'Lingala': 'lin_Latn', 'Lithuanian': 'lit_Latn', 'Lombard': 'lmo_Latn', 'Latgalian': 'ltg_Latn', 'Luxembourgish': 'ltz_Latn', 'Luba-Kasai': 'lua_Latn', 'Ganda': 'lug_Latn', 'Luo': 'luo_Latn', 'Mizo': 'lus_Latn', 'Standard Latvian': 'lvs_Latn', 'Magahi': 'mag_Deva', 'Maithili': 'mai_Deva', 'Malayalam': 'mal_Mlym', 'Marathi': 'mar_Deva', 'Minangkabau Arabic ': 'min_Arab', 'Minangkabau Latin': 'min_Latn', 'Macedonian': 'mkd_Cyrl', 'Plateau Malagasy': 'plt_Latn', 'Maltese': 'mlt_Latn', 'Meitei Bengali': 'mni_Beng', 'Halh Mongolian': 'khk_Cyrl', 'Mossi': 'mos_Latn', 'Maori': 'mri_Latn', 'Burmese': 'mya_Mymr', 'Dutch': 'nld_Latn', 'Norwegian Nynorsk': 'nno_Latn', 'Norwegian Bokmål': 'nob_Latn', 'Nepali': 'npi_Deva', 'Northern Sotho': 'nso_Latn', 'Nuer': 'nus_Latn', 'Nyanja': 'nya_Latn', 'Occitan': 'oci_Latn', 'West Central Oromo': 'gaz_Latn', 'Odia': 'ory_Orya', 'Pangasinan': 'pag_Latn', 'Eastern Panjabi': 'pan_Guru', 'Papiamento': 'pap_Latn', 'Western Persian': 'pes_Arab', 'Polish': 'pol_Latn', 'Portuguese': 'por_Latn', 'Dari': 'prs_Arab', 'Southern Pashto': 'pbt_Arab', 'Ayacucho Quechua': 'quy_Latn', 'Romanian': 'ron_Latn', 'Rundi': 'run_Latn', 'Russian': 'rus_Cyrl', 'Sango': 'sag_Latn', 'Sanskrit': 'san_Deva', 'Santali': 'sat_Olck', 'Sicilian': 'scn_Latn', 'Shan': 'shn_Mymr', 'Sinhala': 'sin_Sinh', 'Slovak': 'slk_Latn', 'Slovenian': 'slv_Latn', 'Samoan': 'smo_Latn', 'Shona': 'sna_Latn', 'Sindhi': 'snd_Arab', 'Somali': 'som_Latn', 'Southern Sotho': 'sot_Latn', 'Spanish': 'spa_Latn', 'Tosk Albanian': 'als_Latn', 'Sardinian': 'srd_Latn', 'Serbian': 'srp_Cyrl', 'Swati': 'ssw_Latn', 'Sundanese': 'sun_Latn', 'Swedish': 'swe_Latn', 'Swahili': 'swh_Latn', 'Silesian': 'szl_Latn', 'Tamil': 'tam_Taml', 'Tatar': 'tat_Cyrl', 'Telugu': 'tel_Telu', 'Tajik': 'tgk_Cyrl', 'Tagalog': 'tgl_Latn', 'Thai': 'tha_Thai', 'Tigrinya': 'tir_Ethi', 'Tamasheq Latin': 'taq_Latn', 'Tamasheq Tifinagh': 'taq_Tfng', 'Tok Pisin': 'tpi_Latn', 'Tswana': 'tsn_Latn', 'Tsonga': 'tso_Latn', 'Turkmen': 'tuk_Latn', 'Tumbuka': 'tum_Latn', 'Turkish': 'tur_Latn', 'Twi': 'twi_Latn', 'Central Atlas Tamazight': 'tzm_Tfng', 'Uyghur': 'uig_Arab', 'Ukrainian': 'ukr_Cyrl', 'Umbundu': 'umb_Latn', 'Urdu': 'urd_Arab', 'Northern Uzbek': 'uzn_Latn', 'Venetian': 'vec_Latn', 'Vietnamese': 'vie_Latn', 'Waray': 'war_Latn', 'Wolof': 'wol_Latn', 'Xhosa': 'xho_Latn', 'Eastern Yiddish': 'ydd_Hebr', 'Yoruba': 'yor_Latn', 'Yue Chinese': 'yue_Hant', 'Chinese Simplified': 'zho_Hans', 'Chinese Traditional': 'zho_Hant', 'Standard Malay': 'zsm_Latn', 'Zulu': 'zul_Latn', } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = "facebook/nllb-200-distilled-600M" snake_case__ = ( "This is a tool that translates text from a language to another. It takes three inputs: `text`, which should " "be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, " "which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in " "plain English, such as 'Romanian', or 'Albanian'. It returns the text translated in `tgt_lang`." ) snake_case__ = "translator" snake_case__ = AutoTokenizer snake_case__ = AutoModelForSeqaSeqLM snake_case__ = LANGUAGE_CODES snake_case__ = ["text", "text", "text"] snake_case__ = ["text"] def a ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if src_lang not in self.lang_to_code: raise ValueError(f'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(f'{tgt_lang} is not a supported language.' ) lowerCAmelCase__ = self.lang_to_code[src_lang] lowerCAmelCase__ = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( SCREAMING_SNAKE_CASE__ , return_tensors="pt" , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ ) def a ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: return self.model.generate(**SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=SCREAMING_SNAKE_CASE__ )
61
0
def snake_case ( lowerCamelCase ): '''simple docstring''' __lowercase = False while is_sorted is False: # Until all the indices are traversed keep looping __lowercase = True for i in range(0 , len(lowerCAmelCase_ ) - 1 , 2 ): # iterating over all even indices if input_list[i] > input_list[i + 1]: __lowercase , __lowercase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowercase = False for i in range(1 , len(lowerCAmelCase_ ) - 1 , 2 ): # iterating over all odd indices if input_list[i] > input_list[i + 1]: __lowercase , __lowercase = input_list[i + 1], input_list[i] # swapping if elements not in order __lowercase = False return input_list if __name__ == "__main__": print("""Enter list to be sorted""") __UpperCamelCase : Any = [int(x) for x in input().split()] # inputing elements of the list in one line __UpperCamelCase : Optional[int] = odd_even_sort(input_list) print("""The sorted list is""") print(sorted_list)
80
import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = VideoToVideoSDPipeline snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"} ) - {"image", "width", "height"} snake_case__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"} ) - {"image"} snake_case__ = PipelineTesterMixin.required_optional_params - {"latents"} snake_case__ = False # No `output_type`. snake_case__ = frozenset( [ "num_inference_steps", "generator", "latents", "return_dict", "callback", "callback_steps", ] ) def a ( self : int ) -> Optional[int]: torch.manual_seed(0 ) lowerCAmelCase__ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) lowerCAmelCase__ = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=SCREAMING_SNAKE_CASE__ , set_alpha_to_one=SCREAMING_SNAKE_CASE__ , ) torch.manual_seed(0 ) lowerCAmelCase__ = 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 , sample_size=128 , ) torch.manual_seed(0 ) lowerCAmelCase__ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act="gelu" , projection_dim=512 , ) lowerCAmelCase__ = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCAmelCase__ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict=0 ) -> Tuple: # 3 frames lowerCAmelCase__ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): lowerCAmelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCAmelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCAmelCase__ = self.get_dummy_components() lowerCAmelCase__ = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = "np" lowerCAmelCase__ = sd_pipe(**SCREAMING_SNAKE_CASE__ ).frames lowerCAmelCase__ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) lowerCAmelCase__ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def a ( self : List[Any] ) -> str: self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , expected_max_diff=5e-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : List[Any] ) -> str: pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def a ( self : int ) -> Optional[Any]: pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def a ( self : List[str] ) -> Optional[int]: pass def a ( self : Optional[Any] ) -> Tuple: return super().test_progress_bar() @slow @skip_mps class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def a ( self : str ) -> int: lowerCAmelCase__ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames lowerCAmelCase__ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCAmelCase__ = torch.randn((1, 10, 3, 1_024, 576) , generator=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = video.to("cuda" ) lowerCAmelCase__ = "Spiderman is surfing" lowerCAmelCase__ = pipe(SCREAMING_SNAKE_CASE__ , video=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=3 , output_type="pt" ).frames lowerCAmelCase__ = np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1e-2
61
0
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class UpperCAmelCase__ ( unittest.TestCase ): def lowerCamelCase_ ( self : Optional[Any] ): _lowerCamelCase : Tuple = get_activation("swish" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0,dtype=torch.floataa ) ).item(),0 ) self.assertNotEqual(act(torch.tensor(-1,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(0,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(2_0,dtype=torch.floataa ) ).item(),2_0 ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : List[str] = get_activation("silu" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,nn.SiLU ) self.assertEqual(act(torch.tensor(-1_0_0,dtype=torch.floataa ) ).item(),0 ) self.assertNotEqual(act(torch.tensor(-1,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(0,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(2_0,dtype=torch.floataa ) ).item(),2_0 ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : int = get_activation("mish" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,nn.Mish ) self.assertEqual(act(torch.tensor(-2_0_0,dtype=torch.floataa ) ).item(),0 ) self.assertNotEqual(act(torch.tensor(-1,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(0,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(2_0,dtype=torch.floataa ) ).item(),2_0 ) def lowerCamelCase_ ( self : List[str] ): _lowerCamelCase : str = get_activation("gelu" ) self.assertIsInstance(SCREAMING_SNAKE_CASE__,nn.GELU ) self.assertEqual(act(torch.tensor(-1_0_0,dtype=torch.floataa ) ).item(),0 ) self.assertNotEqual(act(torch.tensor(-1,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(0,dtype=torch.floataa ) ).item(),0 ) self.assertEqual(act(torch.tensor(2_0,dtype=torch.floataa ) ).item(),2_0 )
44
from __future__ import annotations def _A ( lowerCAmelCase_ : list , lowerCAmelCase_ : int , lowerCAmelCase_ : int , lowerCAmelCase_ : int ): """simple docstring""" lowerCAmelCase__ = [] lowerCAmelCase__ , lowerCAmelCase__ = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) lowerCAmelCase__ = result + left + right return input_list def _A ( lowerCAmelCase_ : list ): """simple docstring""" if len(lowerCAmelCase_ ) <= 1: return input_list lowerCAmelCase__ = list(lowerCAmelCase_ ) # iteration for two-way merging lowerCAmelCase__ = 2 while p <= len(lowerCAmelCase_ ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = i + p - 1 lowerCAmelCase__ = (low + high + 1) // 2 lowerCAmelCase__ = merge(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # final merge of last two parts if p * 2 >= len(lowerCAmelCase_ ): lowerCAmelCase__ = i lowerCAmelCase__ = merge(lowerCAmelCase_ , 0 , lowerCAmelCase_ , len(lowerCAmelCase_ ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": UpperCamelCase = input('Enter numbers separated by a comma:\n').strip() if user_input == "": UpperCamelCase = [] else: UpperCamelCase = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
61
0
import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class SCREAMING_SNAKE_CASE__ (unittest.TestCase ): def snake_case_ ( self): # clean up the VRAM after each test super().tearDown() gc.collect() def snake_case_ ( self): lowercase__ , lowercase__ : Dict = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-canny' , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa) lowercase__ , lowercase__ : Dict = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa) lowercase__ : Optional[int] = controlnet_params lowercase__ : Tuple = 'bird' lowercase__ : Any = jax.device_count() lowercase__ : List[str] = pipe.prepare_text_inputs([prompts] * num_samples) lowercase__ : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png') lowercase__ : str = pipe.prepare_image_inputs([canny_image] * num_samples) lowercase__ : Union[str, Any] = jax.random.PRNGKey(0) lowercase__ : List[str] = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count()) lowercase__ : Tuple = replicate(SCREAMING_SNAKE_CASE__) lowercase__ : Any = shard(SCREAMING_SNAKE_CASE__) lowercase__ : Union[str, Any] = shard(SCREAMING_SNAKE_CASE__) lowercase__ : int = pipe( prompt_ids=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , prng_seed=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , jit=SCREAMING_SNAKE_CASE__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) lowercase__ : List[str] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]) lowercase__ : Tuple = images[0, 253:256, 253:256, -1] lowercase__ : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten())) lowercase__ : Dict = jnp.array( [0.167_969, 0.116_699, 0.081_543, 0.154_297, 0.132_812, 0.108_887, 0.169_922, 0.169_922, 0.205_078]) print(f"""output_slice: {output_slice}""") assert jnp.abs(output_slice - expected_slice).max() < 1e-2 def snake_case_ ( self): lowercase__ , lowercase__ : Dict = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-openpose' , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa) lowercase__ , lowercase__ : Tuple = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ , dtype=jnp.bfloataa) lowercase__ : Dict = controlnet_params lowercase__ : List[Any] = 'Chef in the kitchen' lowercase__ : Any = jax.device_count() lowercase__ : Union[str, Any] = pipe.prepare_text_inputs([prompts] * num_samples) lowercase__ : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png') lowercase__ : Union[str, Any] = pipe.prepare_image_inputs([pose_image] * num_samples) lowercase__ : str = jax.random.PRNGKey(0) lowercase__ : int = jax.random.split(SCREAMING_SNAKE_CASE__ , jax.device_count()) lowercase__ : Optional[Any] = replicate(SCREAMING_SNAKE_CASE__) lowercase__ : Dict = shard(SCREAMING_SNAKE_CASE__) lowercase__ : Dict = shard(SCREAMING_SNAKE_CASE__) lowercase__ : List[Any] = pipe( prompt_ids=SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , prng_seed=SCREAMING_SNAKE_CASE__ , num_inference_steps=50 , jit=SCREAMING_SNAKE_CASE__ , ).images assert images.shape == (jax.device_count(), 1, 768, 512, 3) lowercase__ : Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]) lowercase__ : str = images[0, 253:256, 253:256, -1] lowercase__ : Dict = jnp.asarray(jax.device_get(image_slice.flatten())) lowercase__ : str = jnp.array( [[0.271_484, 0.261_719, 0.275_391, 0.277_344, 0.279_297, 0.291_016, 0.294_922, 0.302_734, 0.302_734]]) print(f"""output_slice: {output_slice}""") assert jnp.abs(output_slice - expected_slice).max() < 1e-2
164
import unittest import numpy as np from transformers import RobertaPreLayerNormConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import ( FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormModel, ) class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=13 , SCREAMING_SNAKE_CASE__ : int=7 , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=99 , SCREAMING_SNAKE_CASE__ : Any=32 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[Any]=4 , SCREAMING_SNAKE_CASE__ : Optional[Any]=37 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=512 , SCREAMING_SNAKE_CASE__ : Tuple=16 , SCREAMING_SNAKE_CASE__ : Optional[Any]=2 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.02 , SCREAMING_SNAKE_CASE__ : Dict=4 , ) -> Optional[int]: lowerCAmelCase__ = parent lowerCAmelCase__ = batch_size lowerCAmelCase__ = seq_length lowerCAmelCase__ = is_training lowerCAmelCase__ = use_attention_mask lowerCAmelCase__ = use_token_type_ids lowerCAmelCase__ = use_labels lowerCAmelCase__ = vocab_size lowerCAmelCase__ = hidden_size lowerCAmelCase__ = num_hidden_layers lowerCAmelCase__ = num_attention_heads lowerCAmelCase__ = intermediate_size lowerCAmelCase__ = hidden_act lowerCAmelCase__ = hidden_dropout_prob lowerCAmelCase__ = attention_probs_dropout_prob lowerCAmelCase__ = max_position_embeddings lowerCAmelCase__ = type_vocab_size lowerCAmelCase__ = type_sequence_label_size lowerCAmelCase__ = initializer_range lowerCAmelCase__ = num_choices def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase__ = None if self.use_attention_mask: lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase__ = None if self.use_token_type_ids: lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase__ = RobertaPreLayerNormConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a ( self : List[str] ) -> Union[str, Any]: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict def a ( self : Optional[Any] ) -> Dict: lowerCAmelCase__ = self.prepare_config_and_inputs() lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs lowerCAmelCase__ = True lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, encoder_hidden_states, encoder_attention_mask, ) @require_flax # Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40 class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = True snake_case__ = ( ( FlaxRobertaPreLayerNormModel, FlaxRobertaPreLayerNormForCausalLM, FlaxRobertaPreLayerNormForMaskedLM, FlaxRobertaPreLayerNormForSequenceClassification, FlaxRobertaPreLayerNormForTokenClassification, FlaxRobertaPreLayerNormForMultipleChoice, FlaxRobertaPreLayerNormForQuestionAnswering, ) if is_flax_available() else () ) def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormModelTester(self ) @slow def a ( self : Tuple ) -> Union[str, Any]: for model_class_name in self.all_model_classes: lowerCAmelCase__ = model_class_name.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_flax class __lowerCamelCase ( unittest.TestCase ): """simple docstring""" @slow def a ( self : int ) -> Dict: lowerCAmelCase__ = FlaxRobertaPreLayerNormForMaskedLM.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] lowerCAmelCase__ = [1, 11, 50_265] self.assertEqual(list(output.shape ) , SCREAMING_SNAKE_CASE__ ) # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[40.4_880, 18.0_199, -5.2_367], [-1.8_877, -4.0_885, 10.7_085], [-2.2_613, -5.6_110, 7.2_665]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @slow def a ( self : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = FlaxRobertaPreLayerNormModel.from_pretrained("andreasmadsen/efficient_mlm_m0.40" , from_pt=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = np.array([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] , dtype=jnp.intaa ) lowerCAmelCase__ = model(SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCAmelCase__ = np.array( [[[0.0_208, -0.0_356, 0.0_237], [-0.1_569, -0.0_411, -0.2_626], [0.1_879, 0.0_125, -0.0_089]]] , dtype=np.floataa ) self.assertTrue(np.allclose(output[:, :3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
61
0
"""simple docstring""" import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() a = logging.get_logger(__name__) set_seed(7_7_0) a = { 'c_attn': 'att_proj', 'c_proj': 'out_proj', 'c_fc': 'in_proj', 'transformer.': '', 'h.': 'layers.', 'ln_1': 'layernorm_1', 'ln_2': 'layernorm_2', 'ln_f': 'layernorm_final', 'wpe': 'position_embeds_layer', 'wte': 'input_embeds_layer', } a = { 'text_small': { 'repo_id': 'suno/bark', 'file_name': 'text.pt', }, 'coarse_small': { 'repo_id': 'suno/bark', 'file_name': 'coarse.pt', }, 'fine_small': { 'repo_id': 'suno/bark', 'file_name': 'fine.pt', }, 'text': { 'repo_id': 'suno/bark', 'file_name': 'text_2.pt', }, 'coarse': { 'repo_id': 'suno/bark', 'file_name': 'coarse_2.pt', }, 'fine': { 'repo_id': 'suno/bark', 'file_name': 'fine_2.pt', }, } a = os.path.dirname(os.path.abspath(__file__)) a = os.path.join(os.path.expanduser('~'), '.cache') a = os.path.join(os.getenv('XDG_CACHE_HOME', default_cache_dir), 'suno', 'bark_v0') def lowercase (snake_case__ : List[Any] , snake_case__ : Tuple=False ) -> int: '''simple docstring''' lowerCAmelCase = model_type if use_small: key += "_small" return os.path.join(lowerCAmelCase_ , REMOTE_MODEL_PATHS[key]["""file_name"""] ) def lowercase (snake_case__ : int , snake_case__ : List[Any] ) -> int: '''simple docstring''' os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) hf_hub_download(repo_id=lowerCAmelCase_ , filename=lowerCAmelCase_ , local_dir=lowerCAmelCase_ ) def lowercase (snake_case__ : Dict , snake_case__ : Any , snake_case__ : List[str]=False , snake_case__ : Optional[Any]="text" ) -> Dict: '''simple docstring''' if model_type == "text": lowerCAmelCase = BarkSemanticModel lowerCAmelCase = BarkSemanticConfig lowerCAmelCase = BarkSemanticGenerationConfig elif model_type == "coarse": lowerCAmelCase = BarkCoarseModel lowerCAmelCase = BarkCoarseConfig lowerCAmelCase = BarkCoarseGenerationConfig elif model_type == "fine": lowerCAmelCase = BarkFineModel lowerCAmelCase = BarkFineConfig lowerCAmelCase = BarkFineGenerationConfig else: raise NotImplementedError() lowerCAmelCase = f'''{model_type}_small''' if use_small else model_type lowerCAmelCase = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(lowerCAmelCase_ ): logger.info(f'''{model_type} model not found, downloading into `{CACHE_DIR}`.''' ) _download(model_info["""repo_id"""] , model_info["""file_name"""] ) lowerCAmelCase = torch.load(lowerCAmelCase_ , map_location=lowerCAmelCase_ ) # this is a hack lowerCAmelCase = checkpoint["""model_args"""] if "input_vocab_size" not in model_args: lowerCAmelCase = model_args["""vocab_size"""] lowerCAmelCase = model_args["""vocab_size"""] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments lowerCAmelCase = model_args.pop("""n_head""" ) lowerCAmelCase = model_args.pop("""n_embd""" ) lowerCAmelCase = model_args.pop("""n_layer""" ) lowerCAmelCase = ConfigClass(**checkpoint["""model_args"""] ) lowerCAmelCase = ModelClass(config=lowerCAmelCase_ ) lowerCAmelCase = GenerationConfigClass() lowerCAmelCase = model_generation_config lowerCAmelCase = checkpoint["""model"""] # fixup checkpoint lowerCAmelCase = """_orig_mod.""" for k, v in list(state_dict.items() ): if k.startswith(lowerCAmelCase_ ): # replace part of the key with corresponding layer name in HF implementation lowerCAmelCase = k[len(lowerCAmelCase_ ) :] for old_layer_name in new_layer_name_dict: lowerCAmelCase = new_k.replace(lowerCAmelCase_ , new_layer_name_dict[old_layer_name] ) lowerCAmelCase = state_dict.pop(lowerCAmelCase_ ) lowerCAmelCase = set(state_dict.keys() ) - set(model.state_dict().keys() ) lowerCAmelCase = {k for k in extra_keys if not k.endswith(""".attn.bias""" )} lowerCAmelCase = set(model.state_dict().keys() ) - set(state_dict.keys() ) lowerCAmelCase = {k for k in missing_keys if not k.endswith(""".attn.bias""" )} if len(lowerCAmelCase_ ) != 0: raise ValueError(f'''extra keys found: {extra_keys}''' ) if len(lowerCAmelCase_ ) != 0: raise ValueError(f'''missing keys: {missing_keys}''' ) model.load_state_dict(lowerCAmelCase_ , strict=lowerCAmelCase_ ) lowerCAmelCase = model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) lowerCAmelCase = checkpoint["""best_val_loss"""].item() logger.info(f'''model loaded: {round(n_params/1e6 , 1 )}M params, {round(lowerCAmelCase_ , 3 )} loss''' ) model.eval() model.to(lowerCAmelCase_ ) del checkpoint, state_dict return model def lowercase (snake_case__ : Tuple , snake_case__ : str=False , snake_case__ : int="text" ) -> List[Any]: '''simple docstring''' if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() lowerCAmelCase = """cpu""" # do conversion on cpu lowerCAmelCase = _get_ckpt_path(lowerCAmelCase_ , use_small=lowerCAmelCase_ ) lowerCAmelCase = _load_model(lowerCAmelCase_ , lowerCAmelCase_ , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) # load bark initial model lowerCAmelCase = _bark_load_model(lowerCAmelCase_ , """cpu""" , model_type=lowerCAmelCase_ , use_small=lowerCAmelCase_ ) if model_type == "text": lowerCAmelCase = bark_model["""model"""] if model.num_parameters(exclude_embeddings=lowerCAmelCase_ ) != bark_model.get_num_params(): raise ValueError("""initial and new models don't have the same number of parameters""" ) # check if same output as the bark model lowerCAmelCase = 5 lowerCAmelCase = 10 if model_type in ["text", "coarse"]: lowerCAmelCase = torch.randint(256 , (batch_size, sequence_length) , dtype=torch.int ) lowerCAmelCase = bark_model(lowerCAmelCase_ )[0] lowerCAmelCase = model(lowerCAmelCase_ ) # take last logits lowerCAmelCase = output_new_model_total.logits[:, [-1], :] else: lowerCAmelCase = 3 lowerCAmelCase = 8 lowerCAmelCase = torch.randint(256 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) lowerCAmelCase = model(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase = bark_model(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("""initial and new outputs don't have the same shape""" ) if (output_new_model - output_old_model).abs().max().item() > 1e-3: raise ValueError("""initial and new outputs are not equal""" ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) def lowercase (snake_case__ : Tuple , snake_case__ : Optional[Any] , snake_case__ : Union[str, Any] , snake_case__ : Optional[int] , snake_case__ : Union[str, Any] , snake_case__ : List[Any] , ) -> Union[str, Any]: '''simple docstring''' lowerCAmelCase = os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase = BarkSemanticConfig.from_pretrained(os.path.join(lowerCAmelCase_ , """config.json""" ) ) lowerCAmelCase = BarkCoarseConfig.from_pretrained(os.path.join(lowerCAmelCase_ , """config.json""" ) ) lowerCAmelCase = BarkFineConfig.from_pretrained(os.path.join(lowerCAmelCase_ , """config.json""" ) ) lowerCAmelCase = EncodecConfig.from_pretrained("""facebook/encodec_24khz""" ) lowerCAmelCase = BarkSemanticModel.from_pretrained(lowerCAmelCase_ ) lowerCAmelCase = BarkCoarseModel.from_pretrained(lowerCAmelCase_ ) lowerCAmelCase = BarkFineModel.from_pretrained(lowerCAmelCase_ ) lowerCAmelCase = EncodecModel.from_pretrained("""facebook/encodec_24khz""" ) lowerCAmelCase = BarkConfig.from_sub_model_configs( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) lowerCAmelCase = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) lowerCAmelCase = BarkModel(lowerCAmelCase_ ) lowerCAmelCase = semantic lowerCAmelCase = coarseAcoustic lowerCAmelCase = fineAcoustic lowerCAmelCase = codec lowerCAmelCase = bark_generation_config Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) bark.save_pretrained(lowerCAmelCase_ , repo_id=lowerCAmelCase_ , push_to_hub=lowerCAmelCase_ ) if __name__ == "__main__": a = argparse.ArgumentParser() # Required parameters parser.add_argument('model_type', type=str, help='text, coarse or fine.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--is_small', action='store_true', help='convert the small version instead of the large.') a = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
169
class __lowerCamelCase : """simple docstring""" def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = size lowerCAmelCase__ = [0] * size lowerCAmelCase__ = [0] * size @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return index | (index + 1) @staticmethod def a ( SCREAMING_SNAKE_CASE__ : int ) -> int: return (index & (index + 1)) - 1 def a ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: lowerCAmelCase__ = value while index < self.size: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) + 1 if current_left_border == index: lowerCAmelCase__ = value else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = self.get_next(SCREAMING_SNAKE_CASE__ ) def a ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: right -= 1 # Because of right is exclusive lowerCAmelCase__ = 0 while left <= right: lowerCAmelCase__ = self.get_prev(SCREAMING_SNAKE_CASE__ ) if left <= current_left: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.tree[right] ) lowerCAmelCase__ = current_left else: lowerCAmelCase__ = max(SCREAMING_SNAKE_CASE__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
61
0
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A__ ( UpperCamelCase__ , unittest.TestCase): _UpperCAmelCase : str = KandinskyImgaImgPipeline _UpperCAmelCase : Optional[int] = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] _UpperCAmelCase : Union[str, Any] = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] _UpperCAmelCase : List[str] = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] _UpperCAmelCase : List[Any] = False @property def UpperCamelCase__ ( self ): return 3_2 @property def UpperCamelCase__ ( self ): return 3_2 @property def UpperCamelCase__ ( self ): return self.time_input_dim @property def UpperCamelCase__ ( self ): return self.time_input_dim * 4 @property def UpperCamelCase__ ( self ): return 1_0_0 @property def UpperCamelCase__ ( self ): lowerCamelCase : Dict = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" ) return tokenizer @property def UpperCamelCase__ ( self ): torch.manual_seed(0 ) lowerCamelCase : Optional[int] = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1_0_0_5 , ) lowerCamelCase : Tuple = MultilingualCLIP(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Optional[Any] = text_encoder.eval() return text_encoder @property def UpperCamelCase__ ( self ): torch.manual_seed(0 ) lowerCamelCase : Union[str, Any] = { """in_channels""": 4, # Out channels is double in channels because predicts mean and variance """out_channels""": 8, """addition_embed_type""": """text_image""", """down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""), """up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""), """mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""", """block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2), """layers_per_block""": 1, """encoder_hid_dim""": self.text_embedder_hidden_size, """encoder_hid_dim_type""": """text_image_proj""", """cross_attention_dim""": self.cross_attention_dim, """attention_head_dim""": 4, """resnet_time_scale_shift""": """scale_shift""", """class_embed_type""": None, } lowerCamelCase : Union[str, Any] = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__ ) return model @property def UpperCamelCase__ ( self ): return { "block_out_channels": [3_2, 6_4], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCamelCase__ ( self ): torch.manual_seed(0 ) lowerCamelCase : Any = VQModel(**self.dummy_movq_kwargs ) return model def UpperCamelCase__ ( self ): lowerCamelCase : List[str] = self.dummy_text_encoder lowerCamelCase : Any = self.dummy_tokenizer lowerCamelCase : Union[str, Any] = self.dummy_unet lowerCamelCase : Dict = self.dummy_movq lowerCamelCase : List[Any] = { """num_train_timesteps""": 1_0_0_0, """beta_schedule""": """linear""", """beta_start""": 0.00_085, """beta_end""": 0.012, """clip_sample""": False, """set_alpha_to_one""": False, """steps_offset""": 0, """prediction_type""": """epsilon""", """thresholding""": False, } lowerCamelCase : Dict = DDIMScheduler(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase : str = { """text_encoder""": text_encoder, """tokenizer""": tokenizer, """unet""": unet, """scheduler""": scheduler, """movq""": movq, } return components def UpperCamelCase__ ( self , __magic_name__ , __magic_name__=0 ): lowerCamelCase : Union[str, Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : str = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(SCREAMING_SNAKE_CASE__ ) # create init_image lowerCamelCase : Optional[int] = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] lowerCamelCase : Optional[Any] = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__ ) ).convert("""RGB""" ).resize((2_5_6, 2_5_6) ) if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): lowerCamelCase : List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: lowerCamelCase : str = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : List[str] = { """prompt""": """horse""", """image""": init_image, """image_embeds""": image_embeds, """negative_image_embeds""": negative_image_embeds, """generator""": generator, """height""": 6_4, """width""": 6_4, """num_inference_steps""": 1_0, """guidance_scale""": 7.0, """strength""": 0.2, """output_type""": """np""", } return inputs def UpperCamelCase__ ( self ): lowerCamelCase : List[str] = """cpu""" lowerCamelCase : Union[str, Any] = self.get_dummy_components() lowerCamelCase : Optional[int] = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Optional[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Optional[int] = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) lowerCamelCase : List[str] = output.images lowerCamelCase : Any = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) , return_dict=SCREAMING_SNAKE_CASE__ , )[0] lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] lowerCamelCase : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) lowerCamelCase : int = np.array( [0.61_474_943, 0.6_073_539, 0.43_308_544, 0.5_928_269, 0.47_493_595, 0.46_755_973, 0.4_613_838, 0.45_368_797, 0.50_119_233] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class A__ ( unittest.TestCase): def UpperCamelCase__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase__ ( self ): lowerCamelCase : List[Any] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/kandinsky_img2img_frog.npy""" ) lowerCamelCase : str = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" ) lowerCamelCase : List[Any] = """A red cartoon frog, 4k""" lowerCamelCase : List[str] = KandinskyPriorPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Optional[Any] = KandinskyImgaImgPipeline.from_pretrained( """kandinsky-community/kandinsky-2-1""" , torch_dtype=torch.floataa ) lowerCamelCase : Any = pipeline.to(SCREAMING_SNAKE_CASE__ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase : Union[str, Any] = torch.Generator(device="""cpu""" ).manual_seed(0 ) lowerCamelCase , lowerCamelCase : Optional[int] = pipe_prior( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple() lowerCamelCase : Union[str, Any] = pipeline( SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , image_embeds=SCREAMING_SNAKE_CASE__ , negative_image_embeds=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=1_0_0 , height=7_6_8 , width=7_6_8 , strength=0.2 , output_type="""np""" , ) lowerCamelCase : Optional[Any] = output.images[0] assert image.shape == (7_6_8, 7_6_8, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
681
import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin UpperCamelCase = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __lowerCamelCase ( UpperCamelCase__ , unittest.TestCase ): """simple docstring""" snake_case__ = XLNetTokenizer snake_case__ = XLNetTokenizerFast snake_case__ = True snake_case__ = True def a ( self : str ) -> str: super().setUp() # We have a SentencePiece fixture for testing lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a ( self : List[str] ) -> List[Any]: lowerCAmelCase__ = "<s>" lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def a ( self : Union[str, Any] ) -> str: lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_006 ) def a ( self : int ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def a ( self : List[str] ) -> Any: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "é", ".", ] , ) lowerCAmelCase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowerCAmelCase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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>", ".", ] , ) def a ( self : Optional[int] ) -> Optional[Any]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def a ( self : List[Any] ) -> Optional[int]: lowerCAmelCase__ = XLNetTokenizer(SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ 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", "se", ".", ] , ) @slow def a ( self : Any ) -> Any: lowerCAmelCase__ = XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowerCAmelCase__ = tokenizer.encode("sequence builders" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.encode("multi-sequence build" , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ ) lowerCAmelCase__ = tokenizer.build_inputs_with_special_tokens(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a ( self : Union[str, Any] ) -> Any: # fmt: off lowerCAmelCase__ = {"input_ids": [[17, 21_442, 270, 17, 10, 14_645, 318, 34, 17, 4_546, 3_145, 787, 13, 7_752, 22_018, 23, 21, 17, 4_546, 3_145, 787, 13, 3_352, 14_431, 13, 5_500, 11, 1_176, 580, 13, 16_819, 4_797, 23, 17, 10, 17_135, 658, 19, 457, 7_932, 13, 184, 19, 3_154, 17_135, 6_468, 19, 1_404, 12_269, 19, 4_229, 5_356, 16_264, 46, 19, 17, 20_545, 10_395, 9, 9, 9, 11, 28, 6_421, 9_531, 20_729, 17, 10, 353, 17_022, 11, 21, 6_421, 9_531, 16_949, 17, 10, 11_509, 753, 11, 33, 95, 2_421, 7_385, 956, 14_431, 2_626, 25, 842, 7_385, 4_836, 21, 1_429, 2_272, 9_855, 3_120, 161, 24_738, 19, 13_203, 658, 218, 787, 21, 430, 18_482, 847, 2_637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22_178, 27, 1_064, 22, 956, 13, 11_101, 1_429, 5_854, 24_313, 18_953, 40, 422, 24_366, 68, 1_758, 37, 10_483, 14_257, 31, 207, 263, 21, 203, 3_773, 25, 71, 9_735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2_049, 3_442, 17, 13_894, 3_380, 23, 95, 18, 17_634, 2_288, 9, 4, 3]], "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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], "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], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 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, 0, 0, 0, 0, 0, 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=SCREAMING_SNAKE_CASE__ , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
61
0
'''simple docstring''' def __UpperCAmelCase ( __magic_name__ )-> Dict: """simple docstring""" snake_case_ : Union[str, Any] = 1 for i in range(1 ,num + 1 ): fact *= i return fact def __UpperCAmelCase ( __magic_name__ )-> str: """simple docstring""" snake_case_ : List[str] = 0 while number > 0: snake_case_ : int = number % 10 sum_of_digits += last_digit snake_case_ : Optional[int] = number // 10 # Removing the last_digit from the given number return sum_of_digits def __UpperCAmelCase ( __magic_name__ = 100 )-> Dict: """simple docstring""" snake_case_ : Optional[int] = factorial(lowerCAmelCase_ ) snake_case_ : List[str] = split_and_add(lowerCAmelCase_ ) return result if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
653
import operator as op UpperCamelCase = 'scaler.pt' UpperCamelCase = 'pytorch_model' UpperCamelCase = 'random_states' UpperCamelCase = 'optimizer' UpperCamelCase = 'scheduler' UpperCamelCase = 'pytorch_model.bin' UpperCamelCase = 'pytorch_model.bin.index.json' UpperCamelCase = 'model.safetensors' UpperCamelCase = 'model.safetensors.index.json' UpperCamelCase = '1.10.2' UpperCamelCase = 'py38' UpperCamelCase = '4.17.0' UpperCamelCase = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] UpperCamelCase = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] UpperCamelCase = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] UpperCamelCase = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] UpperCamelCase = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] UpperCamelCase = '2.0.1' UpperCamelCase = ['pdsh', 'standard', 'openmpi', 'mvapich'] UpperCamelCase = ['default', 'reduce-overhead', 'max-autotune'] UpperCamelCase = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 UpperCamelCase = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] UpperCamelCase = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] UpperCamelCase = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
61
0
'''simple docstring''' import fire from utils import calculate_rouge, save_json def __a(SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : int=None , **SCREAMING_SNAKE_CASE_ : Dict ): '''simple docstring''' _lowerCAmelCase = [x.strip() for x in open(lowerCAmelCase_ ).readlines()] _lowerCAmelCase = [x.strip() for x in open(lowerCAmelCase_ ).readlines()][: len(lowerCAmelCase_ )] _lowerCAmelCase = calculate_rouge(lowerCAmelCase_ , lowerCAmelCase_ , **lowerCAmelCase_ ) if save_path is not None: save_json(lowerCAmelCase_ , lowerCAmelCase_ , indent=lowerCAmelCase_ ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
18
import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = {'vocab_file': 'sentencepiece.model'} UpperCamelCase = { 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } UpperCamelCase = { 'google/rembert': 256, } class __lowerCamelCase ( UpperCamelCase__ ): """simple docstring""" snake_case__ = VOCAB_FILES_NAMES snake_case__ = PRETRAINED_VOCAB_FILES_MAP snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Tuple=True , SCREAMING_SNAKE_CASE__ : Any="[CLS]" , SCREAMING_SNAKE_CASE__ : Optional[int]="[SEP]" , SCREAMING_SNAKE_CASE__ : Dict="[UNK]" , SCREAMING_SNAKE_CASE__ : Optional[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[PAD]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[CLS]" , SCREAMING_SNAKE_CASE__ : List[Any]="[MASK]" , **SCREAMING_SNAKE_CASE__ : str , ) -> Dict: super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) lowerCAmelCase__ = do_lower_case lowerCAmelCase__ = remove_space lowerCAmelCase__ = keep_accents lowerCAmelCase__ = vocab_file lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def a ( self : int ) -> Union[str, Any]: return len(self.sp_model ) def a ( self : Any ) -> str: lowerCAmelCase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> List[str]: lowerCAmelCase__ = self.__dict__.copy() lowerCAmelCase__ = None return state def __setstate__( self : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: lowerCAmelCase__ = d lowerCAmelCase__ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def a ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int=False ) -> Optional[int]: lowerCAmelCase__ = self.sp_model.EncodeAsPieces(SCREAMING_SNAKE_CASE__ ) return pieces def a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def a ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def a ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> int: lowerCAmelCase__ = self.sp_model.decode_pieces(SCREAMING_SNAKE_CASE__ ) return out_string def a ( self : int , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def a ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: lowerCAmelCase__ = [self.sep_token_id] lowerCAmelCase__ = [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 a ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error("Vocabulary path ({}) should be a directory".format(SCREAMING_SNAKE_CASE__ ) ) return lowerCAmelCase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
61
0
"""simple docstring""" import json import re from typing import TYPE_CHECKING, List, Optional, Tuple, Union import numpy as np from ...utils import is_tf_available, is_torch_available, logging if TYPE_CHECKING: if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_codegen import CodeGenTokenizer SCREAMING_SNAKE_CASE__ : Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE__ : Any ={ 'vocab_file': { 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json', }, 'merges_file': { 'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt', }, 'tokenizer_file': { 'Salesforce/codegen-350M-mono': ( 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE__ : Union[str, Any] ={ 'Salesforce/codegen-350M-mono': 2048, } class _UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ["""input_ids""", """attention_mask"""] __snake_case = CodeGenTokenizer def __init__( self , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase="<|endoftext|>" , _lowercase="<|endoftext|>" , _lowercase="<|endoftext|>" , _lowercase=False , **_lowercase , ) -> Optional[int]: super().__init__( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if kwargs.pop('''add_bos_token''' , SCREAMING_SNAKE_CASE__ ): _lowerCamelCase : Any = kwargs.pop('''name_or_path''' , '''''' ) raise ValueError( '''Currenty GPT2\'s fast tokenizer does NOT support adding a BOS token.''' '''Instead you should use GPT2\'s slow tokenizer class `CodeGenTokenizer` as follows: \n''' F'''`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n''' F'''`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n''' '''This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005.''' ''' so that the fast tokenizer works correctly.''' ) _lowerCamelCase : List[str] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , SCREAMING_SNAKE_CASE__ ) != add_prefix_space: _lowerCamelCase : Optional[int] = getattr(SCREAMING_SNAKE_CASE__ , pre_tok_state.pop('''type''' ) ) _lowerCamelCase : Optional[Any] = add_prefix_space _lowerCamelCase : Any = pre_tok_class(**SCREAMING_SNAKE_CASE__ ) _lowerCamelCase : int = add_prefix_space def a__ ( self , *_lowercase , **_lowercase ) -> BatchEncoding: _lowerCamelCase : Optional[Any] = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE__ ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a__ ( self , *_lowercase , **_lowercase ) -> BatchEncoding: _lowerCamelCase : List[Any] = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE__ ) assert self.add_prefix_space or not is_split_into_words, ( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' "to use it with pretokenized inputs." ) return super()._encode_plus(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def a__ ( self , _lowercase , _lowercase = None ) -> Tuple[str]: _lowerCamelCase : Optional[int] = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ ) def a__ ( self , _lowercase , _lowercase = False , _lowercase = None , _lowercase = None , **_lowercase , ) -> str: _lowerCamelCase : Tuple = super().decode( token_ids=SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if truncate_before_pattern is not None and len(SCREAMING_SNAKE_CASE__ ) > 0: _lowerCamelCase : List[str] = self.truncate(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return decoded_text def a__ ( self , _lowercase , _lowercase ) -> Optional[Any]: def find_re(_lowercase , _lowercase , _lowercase ): _lowerCamelCase : int = pattern.search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return m.start() if m else -1 _lowerCamelCase : Optional[int] = [re.compile(SCREAMING_SNAKE_CASE__ , re.MULTILINE ) for pattern in truncate_before_pattern] _lowerCamelCase : Tuple = list(re.finditer('''^print''' , SCREAMING_SNAKE_CASE__ , re.MULTILINE ) ) if len(SCREAMING_SNAKE_CASE__ ) > 1: _lowerCamelCase : List[Any] = completion[: prints[1].start()] _lowerCamelCase : Dict = list(re.finditer('''^def''' , SCREAMING_SNAKE_CASE__ , re.MULTILINE ) ) if len(SCREAMING_SNAKE_CASE__ ) > 1: _lowerCamelCase : int = completion[: defs[1].start()] _lowerCamelCase : Optional[int] = 0 _lowerCamelCase : Tuple = [ pos for pos in [find_re(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for terminal in terminals] if pos != -1 ] if len(SCREAMING_SNAKE_CASE__ ) > 0: return completion[: min(SCREAMING_SNAKE_CASE__ )] else: return completion
434
from ..utils import ( OptionalDependencyNotAvailable, is_flax_available, is_scipy_available, is_torch_available, is_torchsde_available, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_pt_objects import * # noqa F403 else: from .scheduling_consistency_models import CMStochasticIterativeScheduler from .scheduling_ddim import DDIMScheduler from .scheduling_ddim_inverse import DDIMInverseScheduler from .scheduling_ddim_parallel import DDIMParallelScheduler from .scheduling_ddpm import DDPMScheduler from .scheduling_ddpm_parallel import DDPMParallelScheduler from .scheduling_deis_multistep import DEISMultistepScheduler from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler from .scheduling_euler_discrete import EulerDiscreteScheduler from .scheduling_heun_discrete import HeunDiscreteScheduler from .scheduling_ipndm import IPNDMScheduler from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler from .scheduling_karras_ve import KarrasVeScheduler from .scheduling_pndm import PNDMScheduler from .scheduling_repaint import RePaintScheduler from .scheduling_sde_ve import ScoreSdeVeScheduler from .scheduling_sde_vp import ScoreSdeVpScheduler from .scheduling_unclip import UnCLIPScheduler from .scheduling_unipc_multistep import UniPCMultistepScheduler from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin from .scheduling_vq_diffusion import VQDiffusionScheduler try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_flax_objects import * # noqa F403 else: from .scheduling_ddim_flax import FlaxDDIMScheduler from .scheduling_ddpm_flax import FlaxDDPMScheduler from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler from .scheduling_pndm_flax import FlaxPNDMScheduler from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler from .scheduling_utils_flax import ( FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, broadcast_to_shape_from_left, ) try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .scheduling_lms_discrete import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ..utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler
61
0
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = KandinskyVaaPipeline UpperCamelCase_ : List[Any] = [ '''image_embeds''', '''negative_image_embeds''', ] UpperCamelCase_ : Tuple = ['''image_embeds''', '''negative_image_embeds'''] UpperCamelCase_ : Any = [ '''generator''', '''height''', '''width''', '''latents''', '''guidance_scale''', '''num_inference_steps''', '''return_dict''', '''guidance_scale''', '''num_images_per_prompt''', '''output_type''', '''return_dict''', ] UpperCamelCase_ : List[str] = False @property def _A ( self : List[Any] ): return 32 @property def _A ( self : List[Any] ): return 32 @property def _A ( self : Any ): return self.time_input_dim @property def _A ( self : Union[str, Any] ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : Optional[int] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } SCREAMING_SNAKE_CASE : str = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _A ( self : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.dummy_unet SCREAMING_SNAKE_CASE : str = self.dummy_movq SCREAMING_SNAKE_CASE : Optional[int] = DDIMScheduler( num_train_timesteps=1000 , beta_schedule="linear" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , steps_offset=1 , prediction_type="epsilon" , thresholding=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "scheduler": scheduler, "movq": movq, } return components def _A ( self : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any]=0 ): SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Dict = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = { "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "guidance_scale": 4.0, "num_inference_steps": 2, "output_type": "np", } return inputs def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = "cpu" SCREAMING_SNAKE_CASE : Tuple = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**self.get_dummy_inputs(UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Tuple = pipe( **self.get_dummy_inputs(UpperCAmelCase_ ) , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [0.6_237_976, 1.0, 0.36_441_332, 1.0, 0.70_639_634, 0.29_877_186, 0.85_652_125, 0.5_216_843, 0.54_454_046] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy" ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-prior" , torch_dtype=torch.floataa ) pipe_prior.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = KandinskyVaaPipeline.from_pretrained( "kandinsky-community/kandinsky-2-2-decoder" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = "red cat, 4k photo" SCREAMING_SNAKE_CASE : Tuple = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = pipe_prior( UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Generator(device="cuda" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = pipeline( image_embeds=UpperCAmelCase_ , negative_image_embeds=UpperCAmelCase_ , generator=UpperCAmelCase_ , num_inference_steps=100 , output_type="np" , ) SCREAMING_SNAKE_CASE : List[Any] = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ )
62
1
import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_mbart import MBartTokenizer else: snake_case = None snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """facebook/mbart-large-en-ro""": ( """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model""" ), """facebook/mbart-large-cc25""": ( """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model""" ), }, """tokenizer_file""": { """facebook/mbart-large-en-ro""": """https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json""", """facebook/mbart-large-cc25""": """https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json""", }, } snake_case = { """facebook/mbart-large-en-ro""": 1_024, """facebook/mbart-large-cc25""": 1_024, } # fmt: off snake_case = ["""ar_AR""", """cs_CZ""", """de_DE""", """en_XX""", """es_XX""", """et_EE""", """fi_FI""", """fr_XX""", """gu_IN""", """hi_IN""", """it_IT""", """ja_XX""", """kk_KZ""", """ko_KR""", """lt_LT""", """lv_LV""", """my_MM""", """ne_NP""", """nl_XX""", """ro_RO""", """ru_RU""", """si_LK""", """tr_TR""", """vi_VN""", """zh_CN"""] class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[str] = VOCAB_FILES_NAMES UpperCamelCase_ : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : str = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Union[str, Any] = ['''input_ids''', '''attention_mask'''] UpperCamelCase_ : List[str] = MBartTokenizer UpperCamelCase_ : List[int] = [] UpperCamelCase_ : List[int] = [] def __init__( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : Dict=None , UpperCAmelCase_ : Optional[Any]="<s>" , UpperCAmelCase_ : Tuple="</s>" , UpperCAmelCase_ : int="</s>" , UpperCAmelCase_ : List[str]="<s>" , UpperCAmelCase_ : Dict="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Optional[Any]="<mask>" , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : Optional[int]=None , **UpperCAmelCase_ : List[Any] , ): # Mask token behave like a normal word, i.e. include the space before it SCREAMING_SNAKE_CASE : List[Any] = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else mask_token super().__init__( vocab_file=UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , src_lang=UpperCAmelCase_ , tgt_lang=UpperCAmelCase_ , additional_special_tokens=UpperCAmelCase_ , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = vocab_file SCREAMING_SNAKE_CASE : List[str] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : List[str] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} ) SCREAMING_SNAKE_CASE : Optional[Any] = { lang_code: self.convert_tokens_to_ids(UpperCAmelCase_ ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : Any = src_lang if src_lang is not None else "en_XX" SCREAMING_SNAKE_CASE : List[Any] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : Optional[int] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def _A ( self : Union[str, Any] ): return self._src_lang @src_lang.setter def _A ( self : Optional[int] , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : str = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _A ( self : int , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : Any = [self.sep_token_id] SCREAMING_SNAKE_CASE : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _A ( self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] , UpperCAmelCase_ : Optional[str] , **UpperCAmelCase_ : Optional[Any] ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) SCREAMING_SNAKE_CASE : List[Any] = src_lang SCREAMING_SNAKE_CASE : int = self(UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = self.convert_tokens_to_ids(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = tgt_lang_id return inputs def _A ( self : Optional[Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : str = "en_XX" , UpperCAmelCase_ : Optional[List[str]] = None , UpperCAmelCase_ : str = "ro_RO" , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : str = src_lang SCREAMING_SNAKE_CASE : Dict = tgt_lang return super().prepare_seqaseq_batch(UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : List[Any] ): return self.set_src_lang_special_tokens(self.src_lang ) def _A ( self : Any ): return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _A ( self : Any , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : Any = self.convert_tokens_to_ids(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : Union[str, Any] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Any = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : List[Any] = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _A ( self : str , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Dict = self.convert_tokens_to_ids(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = [] SCREAMING_SNAKE_CASE : int = [self.eos_token_id, self.cur_lang_code] SCREAMING_SNAKE_CASE : str = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Dict = processors.TemplateProcessing( single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , ) def _A ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(UpperCAmelCase_ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join( UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCAmelCase_ ): copyfile(self.vocab_file , UpperCAmelCase_ ) return (out_vocab_file,)
62
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput snake_case = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def __init__( self : int , *UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : str=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Tuple=None , **UpperCAmelCase_ : Optional[Any] ): super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = eval_examples SCREAMING_SNAKE_CASE : List[Any] = post_process_function SCREAMING_SNAKE_CASE : Any = quant_trainer_args SCREAMING_SNAKE_CASE : Optional[Any] = 128 # default number of calibration samples def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError("Trainer: calibration requires an calib_dataset." ) SCREAMING_SNAKE_CASE : str = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE : str = self._remove_unused_columns(UpperCAmelCase_ , description="Calibration" ) return DataLoader( UpperCAmelCase_ , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=UpperCAmelCase_ , ) def _A ( self : Optional[int] , UpperCAmelCase_ : Optional[int]=None ): SCREAMING_SNAKE_CASE : Any = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_calib_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args , calib=UpperCAmelCase_ ) model.eval() quant_trainer.enable_calibration(UpperCAmelCase_ ) logger.info("***** Running calibration *****" ) logger.info(f''' Num examples = {self.calib_num}''' ) logger.info(f''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(UpperCAmelCase_ ): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = self.prediction_step(UpperCAmelCase_ , UpperCAmelCase_ , prediction_loss_only=UpperCAmelCase_ ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : Optional[int] = model def _A ( self : List[Any] , UpperCAmelCase_ : int=None , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : str = "eval" ): SCREAMING_SNAKE_CASE : List[str] = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE : Tuple = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Dict = self.compute_metrics SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : int = eval_loop( UpperCAmelCase_ , description="Evaluation" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : int = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE : List[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions ) SCREAMING_SNAKE_CASE : Any = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : Union[str, Any] = metrics.pop(UpperCAmelCase_ ) self.log(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : List[Any] = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) SCREAMING_SNAKE_CASE : List[str] = self.callback_handler.on_evaluate(self.args , self.state , self.control , UpperCAmelCase_ ) return metrics def _A ( self : Optional[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple=None , UpperCAmelCase_ : str = "test" ): SCREAMING_SNAKE_CASE : str = self.get_test_dataloader(UpperCAmelCase_ ) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE : Tuple = self.compute_metrics SCREAMING_SNAKE_CASE : Union[str, Any] = None SCREAMING_SNAKE_CASE : Optional[int] = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE : str = eval_loop( UpperCAmelCase_ , description="Prediction" , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=UpperCAmelCase_ , ) finally: SCREAMING_SNAKE_CASE : Union[str, Any] = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE : Optional[Any] = self.post_process_function(UpperCAmelCase_ , UpperCAmelCase_ , output.predictions , "predict" ) SCREAMING_SNAKE_CASE : str = self.compute_metrics(UpperCAmelCase_ ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(f'''{metric_key_prefix}_''' ): SCREAMING_SNAKE_CASE : str = metrics.pop(UpperCAmelCase_ ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=UpperCAmelCase_ ) def _A ( self : Any , UpperCAmelCase_ : int="./" ): SCREAMING_SNAKE_CASE : List[Any] = self.eval_dataset SCREAMING_SNAKE_CASE : List[Any] = self.get_eval_dataloader(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = next(iter(UpperCAmelCase_ ) ) # saving device - to make it consistent SCREAMING_SNAKE_CASE : int = torch.device("cuda" if torch.cuda.is_available() else "cpu" ) # convert to tuple SCREAMING_SNAKE_CASE : Tuple = tuple(v.to(UpperCAmelCase_ ) for k, v in batch.items() ) logger.info("Converting model to be onnx compatible" ) from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE : List[str] = True SCREAMING_SNAKE_CASE : Any = self.model.to(UpperCAmelCase_ ) model.eval() model.float() SCREAMING_SNAKE_CASE : str = model.module if hasattr(UpperCAmelCase_ , "module" ) else model quant_trainer.configure_model(UpperCAmelCase_ , self.quant_trainer_args ) SCREAMING_SNAKE_CASE : List[Any] = os.path.join(UpperCAmelCase_ , "model.onnx" ) logger.info(f'''exporting model to {output_model_file}''' ) SCREAMING_SNAKE_CASE : int = {0: "batch_size", 1: "seq_len"} torch.onnx.export( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , export_params=UpperCAmelCase_ , opset_version=13 , do_constant_folding=UpperCAmelCase_ , input_names=["input_ids", "attention_mask", "token_type_ids"] , output_names=["output_start_logits", "output_end_logits"] , dynamic_axes={ "input_ids": axes, "attention_mask": axes, "token_type_ids": axes, "output_start_logits": axes, "output_end_logits": axes, } , verbose=UpperCAmelCase_ , ) logger.info("onnx export finished" )
62
1
def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] SCREAMING_SNAKE_CASE : Dict = 6 SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : int = 1901 SCREAMING_SNAKE_CASE : str = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 SCREAMING_SNAKE_CASE : Any = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 SCREAMING_SNAKE_CASE : Tuple = day - 29 else: if day > days_per_month[month - 1]: month += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = day - days_per_month[month - 2] if month > 12: year += 1 SCREAMING_SNAKE_CASE : Union[str, Any] = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
62
import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = LayoutLMTokenizer UpperCamelCase_ : str = LayoutLMTokenizerFast UpperCamelCase_ : Any = True UpperCamelCase_ : Optional[Any] = True def _A ( self : Any ): super().setUp() SCREAMING_SNAKE_CASE : Optional[Any] = [ "[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _A ( self : str , **UpperCAmelCase_ : Optional[int] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = "UNwant\u00E9d,running" SCREAMING_SNAKE_CASE : Union[str, Any] = "unwanted, running" return input_text, output_text def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(UpperCAmelCase_ , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [7, 4, 5, 10, 8, 9] ) def _A ( self : List[str] ): pass
62
1
import copy import re class SCREAMING_SNAKE_CASE : '''simple docstring''' UpperCamelCase_ : List[Any] = '''hp''' UpperCamelCase_ : int = {} UpperCamelCase_ : Optional[Any] = None @classmethod def _A ( cls : int , UpperCAmelCase_ : str , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Tuple = prefix SCREAMING_SNAKE_CASE : int = defaults cls.build_naming_info() @staticmethod def _A ( UpperCAmelCase_ : int , UpperCAmelCase_ : int ): if len(UpperCAmelCase_ ) == 0: return "" SCREAMING_SNAKE_CASE : List[Any] = None if any(char.isdigit() for char in word ): raise Exception(f'''Parameters should not contain numbers: \'{word}\' contains a number''' ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(UpperCAmelCase_ ) + 1 ): SCREAMING_SNAKE_CASE : Tuple = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE : Tuple = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(UpperCAmelCase_ : Optional[int] ): SCREAMING_SNAKE_CASE : Union[str, Any] = "" while integer != 0: SCREAMING_SNAKE_CASE : Tuple = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s SCREAMING_SNAKE_CASE : Tuple = 0 while True: SCREAMING_SNAKE_CASE : Union[str, Any] = word + "#" + int_to_alphabetic(UpperCAmelCase_ ) if sword in info["reverse_short_word"]: continue else: SCREAMING_SNAKE_CASE : Tuple = sword break SCREAMING_SNAKE_CASE : Tuple = short_word SCREAMING_SNAKE_CASE : Tuple = word return short_word @staticmethod def _A ( UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Optional[int] = param_name.split("_" ) SCREAMING_SNAKE_CASE : Union[str, Any] = [TrialShortNamer.shortname_for_word(UpperCAmelCase_ , UpperCAmelCase_ ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name SCREAMING_SNAKE_CASE : List[str] = ["", "_"] for separator in separators: SCREAMING_SNAKE_CASE : Union[str, Any] = separator.join(UpperCAmelCase_ ) if shortname not in info["reverse_short_param"]: SCREAMING_SNAKE_CASE : Union[str, Any] = shortname SCREAMING_SNAKE_CASE : Union[str, Any] = param_name return shortname return param_name @staticmethod def _A ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : int = TrialShortNamer.shortname_for_key(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = short_name SCREAMING_SNAKE_CASE : Union[str, Any] = param_name @classmethod def _A ( cls : Optional[Any] ): if cls.NAMING_INFO is not None: return SCREAMING_SNAKE_CASE : List[Any] = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } SCREAMING_SNAKE_CASE : Any = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = info @classmethod def _A ( cls : List[str] , UpperCAmelCase_ : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None SCREAMING_SNAKE_CASE : Optional[int] = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f'''You should provide a default value for the param name {k} with value {v}''' ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue SCREAMING_SNAKE_CASE : Optional[int] = cls.NAMING_INFO["short_param"][k] if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Optional[int] = 1 if v else 0 SCREAMING_SNAKE_CASE : Union[str, Any] = "" if isinstance(UpperCAmelCase_ , (int, float) ) else "-" SCREAMING_SNAKE_CASE : Any = f'''{key}{sep}{v}''' name.append(UpperCAmelCase_ ) return "_".join(UpperCAmelCase_ ) @classmethod def _A ( cls : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : Optional[Any] = repr[len(cls.PREFIX ) + 1 :] if repr == "": SCREAMING_SNAKE_CASE : Union[str, Any] = [] else: SCREAMING_SNAKE_CASE : List[Any] = repr.split("_" ) SCREAMING_SNAKE_CASE : Tuple = {} for value in values: if "-" in value: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[Any] = value.split("-" ) else: SCREAMING_SNAKE_CASE : List[Any] = re.sub("[0-9.]" , "" , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = float(re.sub("[^0-9.]" , "" , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = cls.NAMING_INFO["reverse_short_param"][p_k] SCREAMING_SNAKE_CASE : List[Any] = p_v for k in cls.DEFAULTS: if k not in parameters: SCREAMING_SNAKE_CASE : Dict = cls.DEFAULTS[k] return parameters
62
import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = os.path.join(args.tf_model_dir , "parameters.json" ) SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(open(lowercase ).read() ) if not params: raise ValueError( F'''It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.''' ) if not args.output.endswith(".pt" ): SCREAMING_SNAKE_CASE : Optional[int] = args.output + ".pt" SCREAMING_SNAKE_CASE : Any = OrderedDict() with tf.device("/CPU:0" ): SCREAMING_SNAKE_CASE : Union[str, Any] = tf.train.load_checkpoint(args.tf_model_dir ) SCREAMING_SNAKE_CASE : Union[str, Any] = reader.get_variable_to_shape_map() for key_name in shapes.keys(): SCREAMING_SNAKE_CASE : Any = reader.get_tensor(lowercase ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9] ) elif key_name.startswith("pasts/out" ): SCREAMING_SNAKE_CASE : Optional[int] = 8 SCREAMING_SNAKE_CASE : List[Any] = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time SCREAMING_SNAKE_CASE : Optional[int] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.startswith("model/moe" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/softmlp/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player SCREAMING_SNAKE_CASE : Any = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): SCREAMING_SNAKE_CASE : Optional[int] = key_name[-9:-7] for i in range(16 ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) SCREAMING_SNAKE_CASE : List[str] = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name.startswith("model/mlp" ): SCREAMING_SNAKE_CASE : str = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): SCREAMING_SNAKE_CASE : Dict = "model.blocks.%d.feed_forward.mlp.wi.weight" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Any = torch.tensor(lowercase ) elif key_name.endswith("/p1/bias" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.mlp.wi.bias" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/kernel" ): SCREAMING_SNAKE_CASE : str = "model.blocks.%d.feed_forward.mlp.wo.weight" % player SCREAMING_SNAKE_CASE : List[Any] = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) elif key_name.endswith("/p2/bias" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.feed_forward.mlp.wo.bias" % player SCREAMING_SNAKE_CASE : str = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) elif key_name.startswith("model/ln" ): SCREAMING_SNAKE_CASE : Union[str, Any] = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.feed_forward.norm.bias" % player SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : List[str] = "model.blocks.%d.feed_forward.norm.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/att" ): SCREAMING_SNAKE_CASE : Optional[int] = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum SCREAMING_SNAKE_CASE : List[str] = state[:, 0, :, :] SCREAMING_SNAKE_CASE : Tuple = state[:, 1, :, :] SCREAMING_SNAKE_CASE : List[Any] = state[:, 2, :, :] SCREAMING_SNAKE_CASE : Tuple = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : List[Any] = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Union[str, Any] = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : int = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[int] = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor(lowercase ) SCREAMING_SNAKE_CASE : Optional[Any] = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(lowercase ) elif key_name.endswith("/o/kernel" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player SCREAMING_SNAKE_CASE : Optional[int] = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif key_name.startswith("model/an" ): SCREAMING_SNAKE_CASE : int = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): SCREAMING_SNAKE_CASE : List[Any] = "model.blocks.%d.self_attn.norm.bias" % player SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : List[str] = torch.tensor(lowercase ) elif key_name.endswith("/g" ): SCREAMING_SNAKE_CASE : Tuple = "model.blocks.%d.self_attn.norm.weight" % player SCREAMING_SNAKE_CASE : List[str] = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): SCREAMING_SNAKE_CASE : str = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] SCREAMING_SNAKE_CASE : List[str] = "model.%s.weight" % nlayer SCREAMING_SNAKE_CASE : Union[str, Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) if key_name.startswith("model/wte" ): SCREAMING_SNAKE_CASE : Union[str, Any] = "lm_head.weight" SCREAMING_SNAKE_CASE : List[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : Dict = torch.tensor(lowercase ) elif key_name.startswith("model/wob" ): SCREAMING_SNAKE_CASE : List[Any] = "final_logits_bias" SCREAMING_SNAKE_CASE : Optional[Any] = vnp.copy() # same in embedded SCREAMING_SNAKE_CASE : List[str] = state.reshape((1, -1) ) SCREAMING_SNAKE_CASE : int = torch.tensor(lowercase ) elif key_name == "model/dense/kernel": SCREAMING_SNAKE_CASE : Optional[int] = "model.last_project.weight" SCREAMING_SNAKE_CASE : Dict = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix SCREAMING_SNAKE_CASE : Tuple = torch.tensor(lowercase ) elif key_name == "model/dense_1/bias": SCREAMING_SNAKE_CASE : str = "model.last_project.bias" SCREAMING_SNAKE_CASE : int = vnp.copy() # same because it is one dimensional SCREAMING_SNAKE_CASE : str = torch.tensor(lowercase ) torch.save(lowercase , args.output ) if __name__ == "__main__": snake_case = argparse.ArgumentParser( description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""") parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""") snake_case = parser.parse_args() convert_tf_gptsan_to_pt(args)
62
1
import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Any , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Optional[Any]=13 , UpperCAmelCase_ : List[str]=30 , UpperCAmelCase_ : Optional[int]=2 , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Tuple=32 , UpperCAmelCase_ : int=5 , UpperCAmelCase_ : str=4 , UpperCAmelCase_ : Union[str, Any]=37 , UpperCAmelCase_ : Tuple="gelu" , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : int=0.1 , UpperCAmelCase_ : List[Any]=10 , UpperCAmelCase_ : Optional[int]=0.02 , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : Tuple=0.6 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : str = batch_size SCREAMING_SNAKE_CASE : List[str] = image_size SCREAMING_SNAKE_CASE : List[Any] = patch_size SCREAMING_SNAKE_CASE : str = num_channels SCREAMING_SNAKE_CASE : Dict = is_training SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : Optional[Any] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : str = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = mask_ratio SCREAMING_SNAKE_CASE : Optional[int] = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE : str = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE : Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[int] = self.get_config() return config, pixel_values, labels def _A ( self : List[str] ): return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCAmelCase_ , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : str = ViTMAEModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : int = model(UpperCAmelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Any = ViTMAEForPreTraining(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = (self.image_size // self.patch_size) ** 2 SCREAMING_SNAKE_CASE : Tuple = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : Optional[int] = ViTMAEForPreTraining(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : str = model(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : Any = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () UpperCamelCase_ : Union[str, Any] = {'''feature-extraction''': ViTMAEModel} if is_torch_available() else {} UpperCamelCase_ : Dict = False UpperCamelCase_ : Tuple = False UpperCamelCase_ : Tuple = False UpperCamelCase_ : int = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : int = ViTMAEModelTester(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = ConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ , hidden_size=37 ) def _A ( self : Any ): self.config_tester.run_common_tests() @unittest.skip(reason="ViTMAE does not use inputs_embeds" ) def _A ( self : Optional[Any] ): pass def _A ( self : str ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Optional[Any] = model_class(UpperCAmelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE : Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCAmelCase_ , nn.Linear ) ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Dict = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Dict = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCAmelCase_ ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): # make masks reproducible np.random.seed(2 ) SCREAMING_SNAKE_CASE : Optional[Any] = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) SCREAMING_SNAKE_CASE : Union[str, Any] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) SCREAMING_SNAKE_CASE : Optional[int] = torch.from_numpy(UpperCAmelCase_ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument SCREAMING_SNAKE_CASE : List[str] = pt_noise super().check_pt_tf_models(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : List[str] = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs[0].cpu().numpy() SCREAMING_SNAKE_CASE : Optional[Any] = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model_class.from_pretrained(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) # Make sure we don't have nans SCREAMING_SNAKE_CASE : List[Any] = after_outputs[0].cpu().numpy() SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : Dict = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(UpperCAmelCase_ , 1E-5 ) @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def _A ( self : Tuple ): pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def _A ( self : Tuple ): pass @unittest.skip( reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load\n to get deterministic results." ) def _A ( self : Optional[Any] ): pass @unittest.skip(reason="ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load" ) def _A ( self : List[str] ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _A ( self : str ): pass @slow def _A ( self : Optional[Any] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Optional[int] = ViTMAEModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Dict ): return ViTImageProcessor.from_pretrained("facebook/vit-mae-base" ) if is_vision_available() else None @slow def _A ( self : int ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) SCREAMING_SNAKE_CASE : Union[str, Any] = ViTMAEForPreTraining.from_pretrained("facebook/vit-mae-base" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : int = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) SCREAMING_SNAKE_CASE : Tuple = ViTMAEConfig() SCREAMING_SNAKE_CASE : Union[str, Any] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) SCREAMING_SNAKE_CASE : Optional[int] = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ , noise=torch.from_numpy(UpperCAmelCase_ ).to(device=UpperCAmelCase_ ) ) # verify the logits SCREAMING_SNAKE_CASE : Tuple = torch.Size((1, 196, 768) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = torch.tensor( [[-0.0_548, -1.7_023, -0.9_325], [0.3_721, -0.5_670, -0.2_233], [0.8_235, -1.3_878, -0.3_524]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , expected_slice.to(UpperCAmelCase_ ) , atol=1E-4 ) )
62
import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE : Any = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"] # fmt: on SCREAMING_SNAKE_CASE : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE : Optional[int] = { "do_resize": True, "size": {"height": 18, "width": 18}, "do_normalize": True, "image_mean": [0.5, 0.5, 0.5], "image_std": [0.5, 0.5, 0.5], } SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(self.tmpdirname , UpperCAmelCase_ ) with open(self.image_processor_file , "w" , encoding="utf-8" ) as fp: json.dump(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] , **UpperCAmelCase_ : List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Union[str, Any] , **UpperCAmelCase_ : Any ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE : Union[str, Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer(bos_token="(BOS)" , eos_token="(EOS)" ) SCREAMING_SNAKE_CASE : Any = self.get_image_processor(do_normalize=UpperCAmelCase_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token="(BOS)" , eos_token="(EOS)" , do_normalize=UpperCAmelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : int = image_processor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Optional[int] = processor(images=UpperCAmelCase_ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = "lower newer" SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[str] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = "lower newer" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , ["input_ids", "token_type_ids", "attention_mask", "pixel_values"] ) # test if it raises when no input is passed with self.assertRaises(UpperCAmelCase_ ): processor() def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.batch_decode(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=UpperCAmelCase_ , image_processor=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = "lower newer" SCREAMING_SNAKE_CASE : Any = self.prepare_image_inputs() SCREAMING_SNAKE_CASE : Dict = processor(text=UpperCAmelCase_ , images=UpperCAmelCase_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
62
1
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
import inspect import unittest from transformers import MobileNetVaConfig 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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "tf_padding" ) ) self.parent.assertTrue(hasattr(UpperCAmelCase_ , "depth_multiplier" ) ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : str , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : List[str]=13 , UpperCAmelCase_ : Any=3 , UpperCAmelCase_ : Union[str, Any]=32 , UpperCAmelCase_ : int=0.25 , UpperCAmelCase_ : Union[str, Any]=8 , UpperCAmelCase_ : Dict=8 , UpperCAmelCase_ : Optional[int]=6 , UpperCAmelCase_ : Optional[Any]=32 , UpperCAmelCase_ : Optional[int]=True , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : str="relu6" , UpperCAmelCase_ : List[str]=1280 , UpperCAmelCase_ : Optional[int]=0.1 , UpperCAmelCase_ : Any=0.02 , UpperCAmelCase_ : Union[str, Any]=True , UpperCAmelCase_ : Tuple=True , UpperCAmelCase_ : Any=10 , UpperCAmelCase_ : Optional[Any]=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Dict = num_channels SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : int = depth_multiplier SCREAMING_SNAKE_CASE : str = depth_divisible_by SCREAMING_SNAKE_CASE : Union[str, Any] = min_depth SCREAMING_SNAKE_CASE : int = expand_ratio SCREAMING_SNAKE_CASE : Tuple = tf_padding SCREAMING_SNAKE_CASE : List[str] = output_stride SCREAMING_SNAKE_CASE : Optional[int] = first_layer_is_expansion SCREAMING_SNAKE_CASE : Any = finegrained_output SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE : Any = classifier_dropout_prob SCREAMING_SNAKE_CASE : Dict = use_labels SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Dict = num_labels SCREAMING_SNAKE_CASE : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE : Union[str, Any] = scope def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE : List[Any] = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE : Tuple = self.get_config() return config, pixel_values, labels, pixel_labels def _A ( self : Optional[int] ): return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , depth_divisible_by=self.depth_divisible_by , min_depth=self.min_depth , expand_ratio=self.expand_ratio , output_stride=self.output_stride , first_layer_is_expansion=self.first_layer_is_expansion , finegrained_output=self.finegrained_output , hidden_act=self.hidden_act , tf_padding=self.tf_padding , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _A ( self : int , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaModel(config=UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ ) 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, ) , ) self.parent.assertEqual( result.pooler_output.shape , (self.batch_size, self.last_hidden_size) , ) def _A ( self : List[str] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : Any ): SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = MobileNetVaForImageClassification(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self : Union[str, Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : Dict = MobileNetVaForSemanticSegmentation(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(UpperCAmelCase_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) SCREAMING_SNAKE_CASE : Any = model(UpperCAmelCase_ , labels=UpperCAmelCase_ ) 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 _A ( self : Any ): SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Any = ( (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation) if is_torch_available() else () ) UpperCamelCase_ : List[Any] = ( { '''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification, '''image-segmentation''': MobileNetVaForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : Any = False UpperCamelCase_ : List[str] = False UpperCamelCase_ : int = False UpperCamelCase_ : str = False def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = MobileNetVaConfigTester(self , config_class=UpperCAmelCase_ , has_text_modality=UpperCAmelCase_ ) def _A ( self : Optional[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV2 does not use inputs_embeds" ) def _A ( self : List[Any] ): pass @unittest.skip(reason="MobileNetV2 does not support input and output embeddings" ) def _A ( self : Dict ): pass @unittest.skip(reason="MobileNetV2 does not output attentions" ) def _A ( self : Union[str, Any] ): pass def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : Tuple = model_class(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : Union[str, Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCAmelCase_ ) def _A ( self : List[Any] ): def check_hidden_states_output(UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = model_class(UpperCAmelCase_ ) model.to(UpperCAmelCase_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**self._prepare_for_class(UpperCAmelCase_ , UpperCAmelCase_ ) ) SCREAMING_SNAKE_CASE : List[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE : Any = 16 self.assertEqual(len(UpperCAmelCase_ ) , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE : str = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE : List[Any] = True check_hidden_states_output(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_ ) @slow def _A ( self : Optional[Any] ): for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : int = MobileNetVaModel.from_pretrained(UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @cached_property def _A ( self : Optional[int] ): return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224" ) if is_vision_available() else None ) @slow def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224" ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE : Optional[int] = prepare_img() SCREAMING_SNAKE_CASE : Optional[int] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ ) # verify the logits SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 1001) ) self.assertEqual(outputs.logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_445, -1.1_993, 0.1_905] ).to(UpperCAmelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase_ , atol=1E-4 ) ) @slow def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : int = model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513" ) SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=UpperCAmelCase_ , return_tensors="pt" ).to(UpperCAmelCase_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE : Dict = torch.Size((1, 21, 65, 65) ) self.assertEqual(logits.shape , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.tensor( [ [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]], [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]], [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]], ] , device=UpperCAmelCase_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , UpperCAmelCase_ , atol=1E-4 ) )
62
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase ): """simple docstring""" def constraint_to_multiple_of(lowercase , lowercase , lowercase=0 , lowercase=None ): SCREAMING_SNAKE_CASE : Any = round(val / multiple ) * multiple if max_val is not None and x > max_val: SCREAMING_SNAKE_CASE : Optional[int] = math.floor(val / multiple ) * multiple if x < min_val: SCREAMING_SNAKE_CASE : int = math.ceil(val / multiple ) * multiple return x SCREAMING_SNAKE_CASE : Tuple = (output_size, output_size) if isinstance(lowercase , lowercase ) else output_size SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = get_image_size(lowercase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = output_size # determine new height and width SCREAMING_SNAKE_CASE : Tuple = output_height / input_height SCREAMING_SNAKE_CASE : List[Any] = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width SCREAMING_SNAKE_CASE : List[str] = scale_width else: # fit height SCREAMING_SNAKE_CASE : Optional[Any] = scale_height SCREAMING_SNAKE_CASE : int = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase ) SCREAMING_SNAKE_CASE : Dict = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase ) return (new_height, new_width) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Any = ['''pixel_values'''] def __init__( self : Any , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Dict[str, int] = None , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[int, float] = 1 / 255 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , **UpperCAmelCase_ : str , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = size if size is not None else {"height": 384, "width": 384} SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : str = keep_aspect_ratio SCREAMING_SNAKE_CASE : int = ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample SCREAMING_SNAKE_CASE : List[str] = do_rescale SCREAMING_SNAKE_CASE : Tuple = rescale_factor SCREAMING_SNAKE_CASE : Union[str, Any] = do_normalize SCREAMING_SNAKE_CASE : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : int = image_std if image_std is not None else IMAGENET_STANDARD_STD def _A ( self : Tuple , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Dict[str, int] , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : PILImageResampling = PILImageResampling.BICUBIC , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : int , ): SCREAMING_SNAKE_CASE : List[str] = get_size_dict(UpperCAmelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE : Optional[Any] = get_resize_output_image_size( UpperCAmelCase_ , output_size=(size["height"], size["width"]) , keep_aspect_ratio=UpperCAmelCase_ , multiple=UpperCAmelCase_ , ) return resize(UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[int, float] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : Dict , ): return rescale(UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Dict , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Union[float, List[float]] , UpperCAmelCase_ : Optional[Union[str, ChannelDimension]] = None , **UpperCAmelCase_ : List[str] , ): return normalize(UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , UpperCAmelCase_ : ImageInput , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : int = None , UpperCAmelCase_ : PILImageResampling = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : float = None , UpperCAmelCase_ : bool = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[float, List[float]]] = None , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : Optional[Any] , ): SCREAMING_SNAKE_CASE : Optional[int] = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE : Optional[int] = get_size_dict(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio SCREAMING_SNAKE_CASE : Optional[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of SCREAMING_SNAKE_CASE : Any = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : Dict = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : Optional[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[int] = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : int = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Tuple = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : List[str] = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : Any = [to_numpy_array(UpperCAmelCase_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE : Tuple = [self.resize(image=UpperCAmelCase_ , size=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE : Tuple = [self.rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ ) for image in images] if do_normalize: SCREAMING_SNAKE_CASE : Optional[Any] = [self.normalize(image=UpperCAmelCase_ , mean=UpperCAmelCase_ , std=UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE : Optional[Any] = {"pixel_values": images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[Tuple] = None ): SCREAMING_SNAKE_CASE : int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(UpperCAmelCase_ ) != len(UpperCAmelCase_ ): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = target_sizes.numpy() SCREAMING_SNAKE_CASE : str = [] for idx in range(len(UpperCAmelCase_ ) ): SCREAMING_SNAKE_CASE : Dict = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode="bilinear" , align_corners=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
62
1
from ...configuration_utils import PretrainedConfig from ...utils import logging snake_case = logging.get_logger(__name__) snake_case = { """naver-clova-ix/donut-base""": """https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json""", # See all Donut models at https://huggingface.co/models?filter=donut-swin } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Tuple = '''donut-swin''' UpperCamelCase_ : List[str] = { '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers''', } def __init__( self : List[Any] , UpperCAmelCase_ : Optional[int]=224 , UpperCAmelCase_ : Any=4 , UpperCAmelCase_ : Optional[Any]=3 , UpperCAmelCase_ : Union[str, Any]=96 , UpperCAmelCase_ : Union[str, Any]=[2, 2, 6, 2] , UpperCAmelCase_ : int=[3, 6, 12, 24] , UpperCAmelCase_ : Dict=7 , UpperCAmelCase_ : Tuple=4.0 , UpperCAmelCase_ : int=True , UpperCAmelCase_ : Optional[Any]=0.0 , UpperCAmelCase_ : Tuple=0.0 , UpperCAmelCase_ : Dict=0.1 , UpperCAmelCase_ : int="gelu" , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Optional[Any]=0.02 , UpperCAmelCase_ : List[Any]=1E-5 , **UpperCAmelCase_ : Any , ): super().__init__(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image_size SCREAMING_SNAKE_CASE : Optional[int] = patch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : int = embed_dim SCREAMING_SNAKE_CASE : Union[str, Any] = depths SCREAMING_SNAKE_CASE : Any = len(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = num_heads SCREAMING_SNAKE_CASE : List[str] = window_size SCREAMING_SNAKE_CASE : Optional[int] = mlp_ratio SCREAMING_SNAKE_CASE : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Dict = drop_path_rate SCREAMING_SNAKE_CASE : Tuple = hidden_act SCREAMING_SNAKE_CASE : List[Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : Tuple = initializer_range # 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(UpperCAmelCase_ ) - 1) )
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : int = 6 ): SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : Optional[int] = Node() SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Optional[int] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node for _ in range(1 , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Tuple = Node() SCREAMING_SNAKE_CASE : Dict = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Union[str, Any] = self.front SCREAMING_SNAKE_CASE : List[str] = previous_node def _A ( self : Union[str, Any] ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def _A ( self : Optional[int] ): self.check_can_perform_operation() return self.front.data if self.front else None def _A ( self : Optional[int] , UpperCAmelCase_ : Any ): if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : List[str] = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Dict = data def _A ( self : List[str] ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[str] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : List[str] = self.front SCREAMING_SNAKE_CASE : List[str] = old_front.next SCREAMING_SNAKE_CASE : Optional[int] = old_front.data SCREAMING_SNAKE_CASE : List[str] = None return data def _A ( self : Any ): if self.is_empty(): raise Exception("Empty Queue" ) def _A ( self : Optional[Any] ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
62
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Tuple = UnCLIPImageVariationPipeline UpperCamelCase_ : Optional[int] = IMAGE_VARIATION_PARAMS - {'''height''', '''width''', '''guidance_scale'''} UpperCamelCase_ : int = IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Optional[Any] = [ '''generator''', '''return_dict''', '''decoder_num_inference_steps''', '''super_res_num_inference_steps''', ] UpperCamelCase_ : Optional[int] = False @property def _A ( self : Optional[int] ): return 32 @property def _A ( self : Any ): return 32 @property def _A ( self : Dict ): return self.time_input_dim @property def _A ( self : Tuple ): return self.time_input_dim * 4 @property def _A ( self : Tuple ): return 100 @property def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : Tuple = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def _A ( self : List[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(UpperCAmelCase_ ) @property def _A ( self : Any ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(UpperCAmelCase_ ) @property def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[Any] = { "clip_embeddings_dim": self.text_embedder_hidden_size, "time_embed_dim": self.time_embed_dim, "cross_attention_dim": self.cross_attention_dim, } SCREAMING_SNAKE_CASE : Optional[int] = UnCLIPTextProjModel(**UpperCAmelCase_ ) return model @property def _A ( self : Union[str, Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = { "sample_size": 32, # RGB in channels "in_channels": 3, # Out channels is double in channels because predicts mean and variance "out_channels": 6, "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": "identity", } SCREAMING_SNAKE_CASE : Dict = UNetaDConditionModel(**UpperCAmelCase_ ) return model @property def _A ( self : int ): return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def _A ( self : Tuple ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def _A ( self : List[str] ): # seeded differently to get different unet than `self.dummy_super_res_first` torch.manual_seed(1 ) SCREAMING_SNAKE_CASE : str = UNetaDModel(**self.dummy_super_res_kwargs ) return model def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = self.dummy_decoder SCREAMING_SNAKE_CASE : str = self.dummy_text_proj SCREAMING_SNAKE_CASE : List[str] = self.dummy_text_encoder SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_tokenizer SCREAMING_SNAKE_CASE : int = self.dummy_super_res_first SCREAMING_SNAKE_CASE : List[str] = self.dummy_super_res_last SCREAMING_SNAKE_CASE : Optional[Any] = UnCLIPScheduler( variance_type="learned_range" , prediction_type="epsilon" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE : int = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="epsilon" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) SCREAMING_SNAKE_CASE : List[Any] = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def _A ( self : Any , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[str]=0 , UpperCAmelCase_ : List[str]=True ): SCREAMING_SNAKE_CASE : Any = floats_tensor((1, 3, 32, 32) , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) if pil_image: SCREAMING_SNAKE_CASE : Optional[int] = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : Tuple = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : str = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE : int = DiffusionPipeline.numpy_to_pil(UpperCAmelCase_ )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = "cpu" SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Any = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = pipe( **UpperCAmelCase_ , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Tuple = np.array( [ 0.9_997, 0.0_002, 0.9_997, 0.9_997, 0.9_969, 0.0_023, 0.9_997, 0.9_969, 0.9_970, ] ) 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 _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Dict = "cpu" SCREAMING_SNAKE_CASE : int = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = pipe( **UpperCAmelCase_ , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Optional[int] = np.array([0.9_997, 0.0_003, 0.9_997, 0.9_997, 0.9_970, 0.0_024, 0.9_997, 0.9_971, 0.9_971] ) 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 _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : Optional[Any] = "cpu" SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = [ pipeline_inputs["image"], pipeline_inputs["image"], ] SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = [ tuple_pipeline_inputs["image"], tuple_pipeline_inputs["image"], ] SCREAMING_SNAKE_CASE : Any = pipe( **UpperCAmelCase_ , return_dict=UpperCAmelCase_ , )[0] SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) SCREAMING_SNAKE_CASE : Any = np.array( [ 0.9_997, 0.9_989, 0.0_008, 0.0_021, 0.9_960, 0.0_018, 0.0_014, 0.0_002, 0.9_933, ] ) 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 _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : str = torch.device("cpu" ) class SCREAMING_SNAKE_CASE : '''simple docstring''' UpperCamelCase_ : Optional[int] = 1 SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.Generator(device=UpperCAmelCase_ ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = pipe.decoder.dtype SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : Union[str, Any] = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) SCREAMING_SNAKE_CASE : List[Any] = pipe.prepare_latents( UpperCAmelCase_ , dtype=UpperCAmelCase_ , device=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE : int = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) SCREAMING_SNAKE_CASE : List[str] = pipe.prepare_latents( UpperCAmelCase_ , dtype=UpperCAmelCase_ , device=UpperCAmelCase_ , generator=UpperCAmelCase_ , latents=UpperCAmelCase_ , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = pipe( **UpperCAmelCase_ , decoder_latents=UpperCAmelCase_ , super_res_latents=UpperCAmelCase_ ).images SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ , pil_image=UpperCAmelCase_ ) # Don't pass image, instead pass embedding SCREAMING_SNAKE_CASE : Tuple = pipeline_inputs.pop("image" ) SCREAMING_SNAKE_CASE : Any = pipe.image_encoder(UpperCAmelCase_ ).image_embeds SCREAMING_SNAKE_CASE : int = pipe( **UpperCAmelCase_ , decoder_latents=UpperCAmelCase_ , super_res_latents=UpperCAmelCase_ , image_embeddings=UpperCAmelCase_ , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = torch_device == "cpu" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor SCREAMING_SNAKE_CASE : Tuple = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=UpperCAmelCase_ , expected_max_diff=UpperCAmelCase_ ) @skip_mps def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Optional[int] = torch_device == "cpu" SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : str = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] self._test_inference_batch_single_identical( test_max_difference=UpperCAmelCase_ , relax_max_difference=UpperCAmelCase_ , additional_params_copy_to_batched_inputs=UpperCAmelCase_ , ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes SCREAMING_SNAKE_CASE : Optional[Any] = [2, 3] self._test_inference_batch_consistent( batch_sizes=UpperCAmelCase_ , additional_params_copy_to_batched_inputs=UpperCAmelCase_ , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=UpperCAmelCase_ ) @skip_mps def _A ( self : Optional[Any] ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def _A ( self : int ): return super().test_save_load_local() @skip_mps def _A ( self : Tuple ): return super().test_save_load_optional_components() @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : str ): SCREAMING_SNAKE_CASE : Any = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png" ) SCREAMING_SNAKE_CASE : int = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/unclip/karlo_v1_alpha_cat_variation_fp16.npy" ) SCREAMING_SNAKE_CASE : Union[str, Any] = UnCLIPImageVariationPipeline.from_pretrained( "kakaobrain/karlo-v1-alpha-image-variations" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : List[str] = pipeline.to(UpperCAmelCase_ ) pipeline.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline( UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , ) SCREAMING_SNAKE_CASE : str = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(UpperCAmelCase_ , UpperCAmelCase_ , 15 )
62
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
1
def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" return 1 if input_a == input_a else 0 def lowerCamelCase__ ( ): """simple docstring""" assert xnor_gate(0 , 0 ) == 1 assert xnor_gate(0 , 1 ) == 0 assert xnor_gate(1 , 0 ) == 0 assert xnor_gate(1 , 1 ) == 1 if __name__ == "__main__": print(xnor_gate(0, 0)) print(xnor_gate(0, 1)) print(xnor_gate(1, 0)) print(xnor_gate(1, 1))
62
import math import flax.linen as nn import jax.numpy as jnp def lowerCamelCase__ ( lowercase , lowercase , lowercase = 1 , lowercase = 1 , lowercase = 1.0E4 , lowercase = False , lowercase = 1.0 , ): """simple docstring""" assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even''' SCREAMING_SNAKE_CASE : Union[str, Any] = float(embedding_dim // 2 ) SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) SCREAMING_SNAKE_CASE : Optional[Any] = min_timescale * jnp.exp(jnp.arange(lowercase , dtype=jnp.floataa ) * -log_timescale_increment ) SCREAMING_SNAKE_CASE : Optional[int] = jnp.expand_dims(lowercase , 1 ) * jnp.expand_dims(lowercase , 0 ) # scale embeddings SCREAMING_SNAKE_CASE : Optional[int] = scale * emb if flip_sin_to_cos: SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase ), jnp.sin(lowercase )] , axis=1 ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.concatenate([jnp.sin(lowercase ), jnp.cos(lowercase )] , axis=1 ) SCREAMING_SNAKE_CASE : Tuple = jnp.reshape(lowercase , [jnp.shape(lowercase )[0], embedding_dim] ) return signal class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : jnp.dtype = jnp.floataa @nn.compact def __call__( self : Tuple , UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_1" )(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = nn.silu(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name="linear_2" )(UpperCAmelCase_ ) return temb class SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' UpperCamelCase_ : int = 3_2 UpperCamelCase_ : bool = False UpperCamelCase_ : float = 1 @nn.compact def __call__( self : Optional[int] , UpperCAmelCase_ : int ): return get_sinusoidal_embeddings( UpperCAmelCase_ , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
62
1
from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar snake_case = TypeVar("""T""") class SCREAMING_SNAKE_CASE ( Generic[T] ): '''simple docstring''' UpperCamelCase_ : deque[T] # Cache store of keys UpperCamelCase_ : set[T] # References of the keys in cache UpperCamelCase_ : int = 1_0 # Maximum capacity of cache def __init__( self : int , UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE : List[Any] = deque() SCREAMING_SNAKE_CASE : Tuple = set() if not n: SCREAMING_SNAKE_CASE : Dict = sys.maxsize elif n < 0: raise ValueError("n should be an integer greater than 0." ) else: SCREAMING_SNAKE_CASE : str = n def _A ( self : Tuple , UpperCAmelCase_ : T ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: SCREAMING_SNAKE_CASE : Union[str, Any] = self.dq_store.pop() self.key_reference.remove(UpperCAmelCase_ ) else: self.dq_store.remove(UpperCAmelCase_ ) self.dq_store.appendleft(UpperCAmelCase_ ) self.key_reference.add(UpperCAmelCase_ ) def _A ( self : Any ): for k in self.dq_store: print(UpperCAmelCase_ ) def __repr__( self : str ): return f'''LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}''' if __name__ == "__main__": import doctest doctest.testmod() snake_case = LRUCache(4) lru_cache.refer("""A""") lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer("""A""") lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
62
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) UpperCamelCase_ : Union[str, Any] = '''CIDAS/clipseg-rd64-refined''' UpperCamelCase_ : Any = '''image_segmenter''' UpperCamelCase_ : int = CLIPSegForImageSegmentation UpperCamelCase_ : Optional[Any] = ['''image''', '''text'''] UpperCamelCase_ : int = ['''image'''] def __init__( self : str , *UpperCAmelCase_ : Union[str, Any] , **UpperCAmelCase_ : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : "Image" , UpperCAmelCase_ : str ): return self.pre_processor(text=[label] , images=[image] , padding=UpperCAmelCase_ , return_tensors="pt" ) def _A ( self : str , UpperCAmelCase_ : Optional[Any] ): with torch.no_grad(): SCREAMING_SNAKE_CASE : str = self.model(**UpperCAmelCase_ ).logits return logits def _A ( self : Union[str, Any] , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
62
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : List[Any] = ['''image_processor''', '''tokenizer'''] UpperCamelCase_ : int = '''BlipImageProcessor''' UpperCamelCase_ : Optional[int] = '''AutoTokenizer''' def __init__( self : Any , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Union[str, Any] , UpperCAmelCase_ : str ): super().__init__(UpperCAmelCase_ , UpperCAmelCase_ ) # add QFormer tokenizer SCREAMING_SNAKE_CASE : Dict = qformer_tokenizer def __call__( self : List[str] , UpperCAmelCase_ : ImageInput = None , UpperCAmelCase_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Union[bool, str, PaddingStrategy] = False , UpperCAmelCase_ : Union[bool, str, TruncationStrategy] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : int = 0 , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : Optional[Union[str, TensorType]] = None , **UpperCAmelCase_ : Optional[Any] , ): if images is None and text is None: raise ValueError("You have to specify at least images or text." ) SCREAMING_SNAKE_CASE : str = BatchFeature() if text is not None: SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) encoding.update(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = self.qformer_tokenizer( text=UpperCAmelCase_ , add_special_tokens=UpperCAmelCase_ , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ , max_length=UpperCAmelCase_ , stride=UpperCAmelCase_ , pad_to_multiple_of=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , return_overflowing_tokens=UpperCAmelCase_ , return_special_tokens_mask=UpperCAmelCase_ , return_offsets_mapping=UpperCAmelCase_ , return_token_type_ids=UpperCAmelCase_ , return_length=UpperCAmelCase_ , verbose=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Optional[Any] = qformer_text_encoding.pop("input_ids" ) SCREAMING_SNAKE_CASE : Dict = qformer_text_encoding.pop("attention_mask" ) if images is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.image_processor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) encoding.update(UpperCAmelCase_ ) return encoding def _A ( self : List[str] , *UpperCAmelCase_ : Optional[int] , **UpperCAmelCase_ : Union[str, Any] ): return self.tokenizer.batch_decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) def _A ( self : List[str] , *UpperCAmelCase_ : Optional[Any] , **UpperCAmelCase_ : Optional[int] ): return self.tokenizer.decode(*UpperCAmelCase_ , **UpperCAmelCase_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _A ( self : int ): SCREAMING_SNAKE_CASE : Any = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE : List[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _A ( self : int , UpperCAmelCase_ : List[str] , **UpperCAmelCase_ : List[Any] ): if os.path.isfile(UpperCAmelCase_ ): raise ValueError(f'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = os.path.join(UpperCAmelCase_ , "qformer_tokenizer" ) self.qformer_tokenizer.save_pretrained(UpperCAmelCase_ ) return super().save_pretrained(UpperCAmelCase_ , **UpperCAmelCase_ ) @classmethod def _A ( cls : List[Any] , UpperCAmelCase_ : List[Any] , **UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : int = AutoTokenizer.from_pretrained(UpperCAmelCase_ , subfolder="qformer_tokenizer" ) SCREAMING_SNAKE_CASE : int = cls._get_arguments_from_pretrained(UpperCAmelCase_ , **UpperCAmelCase_ ) args.append(UpperCAmelCase_ ) return cls(*UpperCAmelCase_ )
62
import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = BlenderbotSmallTokenizer UpperCamelCase_ : int = False def _A ( self : Union[str, Any] ): super().setUp() SCREAMING_SNAKE_CASE : List[Any] = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"] SCREAMING_SNAKE_CASE : Optional[Any] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""] SCREAMING_SNAKE_CASE : int = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"} SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : str = 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(UpperCAmelCase_ ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(UpperCAmelCase_ ) ) def _A ( self : List[Any] , **UpperCAmelCase_ : str ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : int = "adapt act apte" return input_text, output_text def _A ( self : str ): SCREAMING_SNAKE_CASE : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) SCREAMING_SNAKE_CASE : Tuple = "adapt act apte" SCREAMING_SNAKE_CASE : List[str] = ["adapt", "act", "ap@@", "te"] SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer.tokenize(UpperCAmelCase_ ) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] SCREAMING_SNAKE_CASE : Tuple = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , UpperCAmelCase_ ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) assert tok("sam" ).input_ids == [1384] SCREAMING_SNAKE_CASE : str = "I am a small frog." SCREAMING_SNAKE_CASE : List[Any] = tok([src_text] , padding=UpperCAmelCase_ , truncation=UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : int = tok.batch_decode(UpperCAmelCase_ , skip_special_tokens=UpperCAmelCase_ , clean_up_tokenization_spaces=UpperCAmelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[str] = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M" ) SCREAMING_SNAKE_CASE : Tuple = "I am a small frog ." SCREAMING_SNAKE_CASE : Optional[int] = "." SCREAMING_SNAKE_CASE : Dict = tok(UpperCAmelCase_ )["input_ids"] SCREAMING_SNAKE_CASE : Optional[Any] = tok(UpperCAmelCase_ )["input_ids"] assert encoded[-1] == encoded_dot[0]
62
1
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def lowerCamelCase__ ( lowercase ): """simple docstring""" if is_torch_version("<" , "2.0.0" ) or not hasattr(lowercase , "_dynamo" ): return False return isinstance(lowercase , torch._dynamo.eval_frame.OptimizedModule ) def lowerCamelCase__ ( lowercase , lowercase = True ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE : Optional[int] = is_compiled_module(lowercase ) if is_compiled: SCREAMING_SNAKE_CASE : Optional[Any] = model SCREAMING_SNAKE_CASE : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[str] = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE : Tuple = getattr(lowercase , "forward" ) SCREAMING_SNAKE_CASE : Any = model.__dict__.pop("_original_forward" , lowercase ) if original_forward is not None: while hasattr(lowercase , "__wrapped__" ): SCREAMING_SNAKE_CASE : Any = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE : Optional[Any] = forward if getattr(lowercase , "_converted_to_transformer_engine" , lowercase ): convert_model(lowercase , to_transformer_engine=lowercase ) if is_compiled: SCREAMING_SNAKE_CASE : str = model SCREAMING_SNAKE_CASE : Optional[Any] = compiled_model return model def lowerCamelCase__ ( ): """simple docstring""" PartialState().wait_for_everyone() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase , lowercase ) elif PartialState().local_process_index == 0: torch.save(lowercase , lowercase ) @contextmanager def lowerCamelCase__ ( **lowercase ): """simple docstring""" for key, value in kwargs.items(): SCREAMING_SNAKE_CASE : str = str(lowercase ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def lowerCamelCase__ ( lowercase ): """simple docstring""" if not hasattr(lowercase , "__qualname__" ) and not hasattr(lowercase , "__name__" ): SCREAMING_SNAKE_CASE : int = getattr(lowercase , "__class__" , lowercase ) if hasattr(lowercase , "__qualname__" ): return obj.__qualname__ if hasattr(lowercase , "__name__" ): return obj.__name__ return str(lowercase ) def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" for key, value in source.items(): if isinstance(lowercase , lowercase ): SCREAMING_SNAKE_CASE : List[str] = destination.setdefault(lowercase , {} ) merge_dicts(lowercase , lowercase ) else: SCREAMING_SNAKE_CASE : Any = value return destination def lowerCamelCase__ ( lowercase = None ): """simple docstring""" if port is None: SCREAMING_SNAKE_CASE : str = 29500 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(("localhost", port) ) == 0
62
import argparse from collections import OrderedDict from pathlib import Path import torch from transformers import ( VisualBertConfig, VisualBertForMultipleChoice, VisualBertForPreTraining, VisualBertForQuestionAnswering, VisualBertForVisualReasoning, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) snake_case = [ ("""bert.bert""", """visual_bert"""), ("""bert.cls""", """cls"""), ("""bert.classifier""", """cls"""), ("""token_type_embeddings_visual""", """visual_token_type_embeddings"""), ("""position_embeddings_visual""", """visual_position_embeddings"""), ("""projection""", """visual_projection"""), ] snake_case = [ """nlvr2_coco_pre_trained.th""", """nlvr2_fine_tuned.th""", """nlvr2_pre_trained.th""", """vcr_coco_pre_train.th""", """vcr_fine_tune.th""", """vcr_pre_train.th""", """vqa_coco_pre_trained.th""", """vqa_fine_tuned.th""", """vqa_pre_trained.th""", ] def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = torch.load(lowercase , map_location="cpu" ) return sd def lowerCamelCase__ ( lowercase , lowercase , lowercase=rename_keys_prefix ): """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = OrderedDict() SCREAMING_SNAKE_CASE : Union[str, Any] = torch.arange(config.max_position_embeddings ).expand((1, -1) ) # detector_d = OrderedDict() for key in d: if "detector" in key: # detector_d[key.replace('detector.','')] = d[key] continue SCREAMING_SNAKE_CASE : Union[str, Any] = key for name_pair in rename_keys_prefix: SCREAMING_SNAKE_CASE : Any = new_key.replace(name_pair[0] , name_pair[1] ) SCREAMING_SNAKE_CASE : Dict = d[key] if key == "bert.cls.predictions.decoder.weight": # Old bert code didn't have `decoder.bias`, but was added separately SCREAMING_SNAKE_CASE : Union[str, Any] = new_d["cls.predictions.bias"] return new_d @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase ): """simple docstring""" assert ( checkpoint_path.split("/" )[-1] in ACCEPTABLE_CHECKPOINTS ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.''' # Get Config if "pre" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = "pretraining" if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = {"visual_embedding_dim": 512} elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[Any] = {"visual_embedding_dim": 2048} elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Any = {"visual_embedding_dim": 2048} elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 1024} else: raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.''' ) else: if "vcr" in checkpoint_path: SCREAMING_SNAKE_CASE : str = {"visual_embedding_dim": 512} SCREAMING_SNAKE_CASE : Tuple = "multichoice" elif "vqa_advanced" in checkpoint_path: SCREAMING_SNAKE_CASE : List[str] = {"visual_embedding_dim": 2048} SCREAMING_SNAKE_CASE : str = "vqa_advanced" elif "vqa" in checkpoint_path: SCREAMING_SNAKE_CASE : Tuple = {"visual_embedding_dim": 2048, "num_labels": 3129} SCREAMING_SNAKE_CASE : Optional[Any] = "vqa" elif "nlvr" in checkpoint_path: SCREAMING_SNAKE_CASE : int = { "visual_embedding_dim": 1024, "num_labels": 2, } SCREAMING_SNAKE_CASE : Tuple = "nlvr" SCREAMING_SNAKE_CASE : List[Any] = VisualBertConfig(**lowercase ) # Load State Dict SCREAMING_SNAKE_CASE : List[str] = load_state_dict(lowercase ) SCREAMING_SNAKE_CASE : Any = get_new_dict(lowercase , lowercase ) if model_type == "pretraining": SCREAMING_SNAKE_CASE : int = VisualBertForPreTraining(lowercase ) elif model_type == "vqa": SCREAMING_SNAKE_CASE : Tuple = VisualBertForQuestionAnswering(lowercase ) elif model_type == "nlvr": SCREAMING_SNAKE_CASE : List[Any] = VisualBertForVisualReasoning(lowercase ) elif model_type == "multichoice": SCREAMING_SNAKE_CASE : Optional[Any] = VisualBertForMultipleChoice(lowercase ) model.load_state_dict(lowercase ) # Save Checkpoints Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument("""orig_checkpoint_path""", type=str, help="""A path to .th on local filesystem.""") parser.add_argument("""pytorch_dump_folder_path""", type=str, help="""Path to the output PyTorch model.""") snake_case = parser.parse_args() convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
62
1
def lowerCamelCase__ ( ): """simple docstring""" return 1 def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else two_pence(x - 2 ) + one_pence() def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else five_pence(x - 5 ) + two_pence(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else ten_pence(x - 10 ) + five_pence(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else twenty_pence(x - 20 ) + ten_pence(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else fifty_pence(x - 50 ) + twenty_pence(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else one_pound(x - 100 ) + fifty_pence(lowercase ) def lowerCamelCase__ ( lowercase ): """simple docstring""" return 0 if x < 0 else two_pound(x - 200 ) + one_pound(lowercase ) def lowerCamelCase__ ( lowercase = 200 ): """simple docstring""" return two_pound(lowercase ) if __name__ == "__main__": print(solution(int(input().strip())))
62
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case = { """configuration_jukebox""": [ """JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP""", """JukeboxConfig""", """JukeboxPriorConfig""", """JukeboxVQVAEConfig""", ], """tokenization_jukebox""": ["""JukeboxTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case = [ """JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST""", """JukeboxModel""", """JukeboxPreTrainedModel""", """JukeboxVQVAE""", """JukeboxPrior""", ] if TYPE_CHECKING: from .configuration_jukebox import ( JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig, ) from .tokenization_jukebox import JukeboxTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_jukebox import ( JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST, JukeboxModel, JukeboxPreTrainedModel, JukeboxPrior, JukeboxVQVAE, ) else: import sys snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
62
1
import json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoProcessor from transformers.models.wavaveca import WavaVecaCTCTokenizer, WavaVecaFeatureExtractor from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wavaveca.test_feature_extraction_wavaveca import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wavaveca_with_lm import WavaVecaProcessorWithLM from transformers.models.wavaveca_with_lm.processing_wavaveca_with_lm import WavaVecaDecoderWithLMOutput if is_torch_available(): from transformers import WavaVecaForCTC @require_pyctcdecode class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : str ): SCREAMING_SNAKE_CASE : Optional[int] = "| <pad> <unk> <s> </s> a b c d e f g h i j k".split() SCREAMING_SNAKE_CASE : Optional[int] = dict(zip(UpperCAmelCase_ , range(len(UpperCAmelCase_ ) ) ) ) SCREAMING_SNAKE_CASE : List[Any] = { "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", } SCREAMING_SNAKE_CASE : Any = { "feature_size": 1, "padding_value": 0.0, "sampling_rate": 1_6000, "return_attention_mask": False, "do_normalize": True, } SCREAMING_SNAKE_CASE : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) SCREAMING_SNAKE_CASE : int = os.path.join(self.tmpdirname , UpperCAmelCase_ ) with open(self.vocab_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + "\n" ) with open(self.feature_extraction_file , "w" , encoding="utf-8" ) as fp: fp.write(json.dumps(UpperCAmelCase_ ) + "\n" ) # load decoder from hub SCREAMING_SNAKE_CASE : List[str] = "hf-internal-testing/ngram-beam-search-decoder" def _A ( self : int , **UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : int = self.add_kwargs_tokens_map.copy() kwargs.update(UpperCAmelCase_ ) return WavaVecaCTCTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : str , **UpperCAmelCase_ : List[str] ): return WavaVecaFeatureExtractor.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def _A ( self : Optional[Any] , **UpperCAmelCase_ : Optional[int] ): return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name , **UpperCAmelCase_ ) def _A ( self : List[Any] ): shutil.rmtree(self.tmpdirname ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : int = self.get_tokenizer() SCREAMING_SNAKE_CASE : Any = self.get_feature_extractor() SCREAMING_SNAKE_CASE : List[str] = self.get_decoder() SCREAMING_SNAKE_CASE : List[Any] = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : str = WavaVecaProcessorWithLM.from_pretrained(self.tmpdirname ) # tokenizer self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCAmelCase_ ) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCAmelCase_ ) # decoder self.assertEqual(processor.decoder._alphabet.labels , decoder._alphabet.labels ) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set , decoder.model_container[decoder._model_key]._unigram_set , ) self.assertIsInstance(processor.decoder , UpperCAmelCase_ ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : List[str] = WavaVecaProcessorWithLM( tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname ) # make sure that error is thrown when decoder alphabet doesn't match SCREAMING_SNAKE_CASE : List[str] = WavaVecaProcessorWithLM.from_pretrained( self.tmpdirname , alpha=5.0 , beta=3.0 , score_boundary=-7.0 , unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha , 5.0 ) self.assertEqual(processor.language_model.beta , 3.0 ) self.assertEqual(processor.language_model.score_boundary , -7.0 ) self.assertEqual(processor.language_model.unk_score_offset , 3 ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : int = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["xx"] ) with self.assertRaisesRegex(UpperCAmelCase_ , "include" ): WavaVecaProcessorWithLM( tokenizer=UpperCAmelCase_ , feature_extractor=self.get_feature_extractor() , decoder=self.get_decoder() ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Tuple = self.get_feature_extractor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[Any] = self.get_decoder() SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = floats_list((3, 1000) ) SCREAMING_SNAKE_CASE : Tuple = feature_extractor(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Any = processor(UpperCAmelCase_ , return_tensors="np" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : str = self.get_tokenizer() SCREAMING_SNAKE_CASE : List[Any] = self.get_decoder() SCREAMING_SNAKE_CASE : int = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = "This is a test string" SCREAMING_SNAKE_CASE : List[str] = processor(text=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(UpperCAmelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _A ( self : str , UpperCAmelCase_ : List[Any]=(2, 10, 16) , UpperCAmelCase_ : Optional[Any]=77 ): np.random.seed(UpperCAmelCase_ ) return np.random.rand(*UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_decoder() SCREAMING_SNAKE_CASE : Optional[Any] = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = self._get_dummy_logits(shape=(10, 16) , seed=13 ) SCREAMING_SNAKE_CASE : Optional[Any] = processor.decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = decoder.decode_beams(UpperCAmelCase_ )[0] self.assertEqual(decoded_decoder[0] , decoded_processor.text ) self.assertEqual("</s> <s> </s>" , decoded_processor.text ) self.assertEqual(decoded_decoder[-2] , decoded_processor.logit_score ) self.assertEqual(decoded_decoder[-1] , decoded_processor.lm_score ) @parameterized.expand([[None], ["fork"], ["spawn"]] ) def _A ( self : str , UpperCAmelCase_ : Tuple ): SCREAMING_SNAKE_CASE : List[str] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_decoder() SCREAMING_SNAKE_CASE : List[str] = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: SCREAMING_SNAKE_CASE : Optional[int] = processor.batch_decode(UpperCAmelCase_ ) else: with get_context(UpperCAmelCase_ ).Pool() as pool: SCREAMING_SNAKE_CASE : List[Any] = processor.batch_decode(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = list(UpperCAmelCase_ ) with get_context("fork" ).Pool() as p: SCREAMING_SNAKE_CASE : Optional[Any] = decoder.decode_beams_batch(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0] ) logit_scores_decoder.append(beams[0][-2] ) lm_scores_decoder.append(beams[0][-1] ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.text ) self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"] , decoded_processor.text ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.logit_score ) self.assertListEqual(UpperCAmelCase_ , decoded_processor.lm_score ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE : Any = self.get_decoder() SCREAMING_SNAKE_CASE : List[Any] = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = self._get_dummy_logits() SCREAMING_SNAKE_CASE : Union[str, Any] = 15 SCREAMING_SNAKE_CASE : Optional[int] = -20.0 SCREAMING_SNAKE_CASE : Optional[Any] = -4.0 SCREAMING_SNAKE_CASE : Optional[Any] = processor.batch_decode( UpperCAmelCase_ , beam_width=UpperCAmelCase_ , beam_prune_logp=UpperCAmelCase_ , token_min_logp=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Union[str, Any] = decoded_processor_out.text SCREAMING_SNAKE_CASE : Optional[Any] = list(UpperCAmelCase_ ) with get_context("fork" ).Pool() as pool: SCREAMING_SNAKE_CASE : List[Any] = decoder.decode_beams_batch( UpperCAmelCase_ , UpperCAmelCase_ , beam_width=UpperCAmelCase_ , beam_prune_logp=UpperCAmelCase_ , token_min_logp=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Tuple = [d[0][0] for d in decoded_decoder_out] SCREAMING_SNAKE_CASE : Union[str, Any] = [d[0][2] for d in decoded_decoder_out] SCREAMING_SNAKE_CASE : Optional[Any] = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"] , UpperCAmelCase_ ) self.assertTrue(np.array_equal(UpperCAmelCase_ , decoded_processor_out.logit_score ) ) self.assertTrue(np.allclose([-20.054, -18.447] , UpperCAmelCase_ , atol=1E-3 ) ) self.assertTrue(np.array_equal(UpperCAmelCase_ , decoded_processor_out.lm_score ) ) self.assertTrue(np.allclose([-15.554, -13.9_474] , UpperCAmelCase_ , atol=1E-3 ) ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Optional[int] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_decoder() SCREAMING_SNAKE_CASE : int = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = self._get_dummy_logits() SCREAMING_SNAKE_CASE : Optional[int] = 2.0 SCREAMING_SNAKE_CASE : Tuple = 5.0 SCREAMING_SNAKE_CASE : Dict = -20.0 SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : str = processor.batch_decode( UpperCAmelCase_ , alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , unk_score_offset=UpperCAmelCase_ , lm_score_boundary=UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : List[Any] = decoded_processor_out.text SCREAMING_SNAKE_CASE : Any = list(UpperCAmelCase_ ) decoder.reset_params( alpha=UpperCAmelCase_ , beta=UpperCAmelCase_ , unk_score_offset=UpperCAmelCase_ , lm_score_boundary=UpperCAmelCase_ , ) with get_context("fork" ).Pool() as pool: SCREAMING_SNAKE_CASE : Tuple = decoder.decode_beams_batch( UpperCAmelCase_ , UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : Any = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"] , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha , 2.0 ) self.assertEqual(lm_model.beta , 5.0 ) self.assertEqual(lm_model.unk_score_offset , -20.0 ) self.assertEqual(lm_model.score_boundary , UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : int = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : Any = processor.decoder.model_container[processor.decoder._model_key] SCREAMING_SNAKE_CASE : Optional[Any] = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() SCREAMING_SNAKE_CASE : Tuple = os.listdir(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = ["alphabet.json", "language_model"] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[str] ): SCREAMING_SNAKE_CASE : List[str] = snapshot_download("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : str = WavaVecaProcessorWithLM.from_pretrained(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = processor.decoder.model_container[processor.decoder._model_key] SCREAMING_SNAKE_CASE : Tuple = Path(language_model._kenlm_model.path.decode("utf-8" ) ).parent.parent.absolute() SCREAMING_SNAKE_CASE : List[Any] = os.listdir(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = os.listdir(UpperCAmelCase_ ) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Optional[int] = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : str = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : Tuple = floats_list((3, 1000) ) SCREAMING_SNAKE_CASE : str = processor_wavaveca(UpperCAmelCase_ , return_tensors="np" ) SCREAMING_SNAKE_CASE : Union[str, Any] = processor_auto(UpperCAmelCase_ , return_tensors="np" ) for key in input_wavaveca.keys(): self.assertAlmostEqual(input_wavaveca[key].sum() , input_auto[key].sum() , delta=1E-2 ) SCREAMING_SNAKE_CASE : Dict = self._get_dummy_logits() SCREAMING_SNAKE_CASE : List[Any] = processor_wavaveca.batch_decode(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = processor_auto.batch_decode(UpperCAmelCase_ ) self.assertListEqual(decoded_wavaveca.text , decoded_auto.text ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : List[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE : Dict = self.get_decoder() SCREAMING_SNAKE_CASE : int = WavaVecaProcessorWithLM(tokenizer=UpperCAmelCase_ , feature_extractor=UpperCAmelCase_ , decoder=UpperCAmelCase_ ) self.assertListEqual( processor.model_input_names , feature_extractor.model_input_names , msg="`processor` and `feature_extractor` model input names do not match" , ) @staticmethod def _A ( UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[Any] ): SCREAMING_SNAKE_CASE : str = [d[key] for d in offsets] return retrieved_list def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Tuple = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : Dict = self._get_dummy_logits()[0] SCREAMING_SNAKE_CASE : Dict = processor.decode(UpperCAmelCase_ , output_word_offsets=UpperCAmelCase_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"] , "word" ) ) , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"] , "end_offset" ) , [1, 3, 5] ) def _A ( self : str ): SCREAMING_SNAKE_CASE : int = WavaVecaProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm" ) SCREAMING_SNAKE_CASE : Optional[int] = self._get_dummy_logits() SCREAMING_SNAKE_CASE : List[Any] = processor.batch_decode(UpperCAmelCase_ , output_word_offsets=UpperCAmelCase_ ) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys() ) , 4 ) self.assertTrue("text" in outputs ) self.assertTrue("word_offsets" in outputs ) self.assertTrue(isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) ) self.assertListEqual( [" ".join(self.get_from_offsets(UpperCAmelCase_ , "word" ) ) for o in outputs["word_offsets"]] , outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "word" ) , ["<s>", "<s>", "</s>"] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "start_offset" ) , [0, 2, 4] ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0] , "end_offset" ) , [1, 3, 5] ) @slow @require_torch @require_torchaudio def _A ( self : List[str] ): import torch SCREAMING_SNAKE_CASE : Any = load_dataset("common_voice" , "en" , split="train" , streaming=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = ds.cast_column("audio" , datasets.Audio(sampling_rate=1_6000 ) ) SCREAMING_SNAKE_CASE : Dict = iter(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = next(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) SCREAMING_SNAKE_CASE : Union[str, Any] = WavaVecaForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm" ) # compare to filename `common_voice_en_100038.mp3` of dataset viewer on https://huggingface.co/datasets/common_voice/viewer/en/train SCREAMING_SNAKE_CASE : Union[str, Any] = processor(sample["audio"]["array"] , return_tensors="pt" ).input_values with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(UpperCAmelCase_ ).logits.cpu().numpy() SCREAMING_SNAKE_CASE : List[str] = processor.decode(logits[0] , output_word_offsets=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate SCREAMING_SNAKE_CASE : List[Any] = [ { "start_time": d["start_offset"] * time_offset, "end_time": d["end_offset"] * time_offset, "word": d["word"], } for d in output["word_offsets"] ] SCREAMING_SNAKE_CASE : List[Any] = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" # output words self.assertEqual(" ".join(self.get_from_offsets(UpperCAmelCase_ , "word" ) ) , UpperCAmelCase_ ) self.assertEqual(" ".join(self.get_from_offsets(UpperCAmelCase_ , "word" ) ) , output.text ) # output times SCREAMING_SNAKE_CASE : Tuple = torch.tensor(self.get_from_offsets(UpperCAmelCase_ , "start_time" ) ) SCREAMING_SNAKE_CASE : Dict = torch.tensor(self.get_from_offsets(UpperCAmelCase_ , "end_time" ) ) # fmt: off SCREAMING_SNAKE_CASE : List[str] = torch.tensor([1.4_199, 1.6_599, 2.2_599, 3.0, 3.24, 3.5_999, 3.7_999, 4.0_999, 4.26, 4.94, 5.28, 5.6_599, 5.78, 5.94, 6.32, 6.5_399, 6.6_599] ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([1.5_399, 1.8_999, 2.9, 3.16, 3.5_399, 3.72, 4.0_199, 4.1_799, 4.76, 5.1_599, 5.5_599, 5.6_999, 5.86, 6.1_999, 6.38, 6.6_199, 6.94] ) # fmt: on self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=0.01 ) ) self.assertTrue(torch.allclose(UpperCAmelCase_ , UpperCAmelCase_ , atol=0.01 ) )
62
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo snake_case = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ snake_case = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ snake_case = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results[\"google_bleu\"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results[\"google_bleu\"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric(\"google_bleu\") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results[\"google_bleu\"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def _A ( self : Optional[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string" , id="token" ) , id="sequence" ) , id="references" ), } ) , ) def _A ( self : List[Any] , UpperCAmelCase_ : List[List[List[str]]] , UpperCAmelCase_ : List[List[str]] , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : int = 4 , ): return { "google_bleu": gleu_score.corpus_gleu( list_of_references=UpperCAmelCase_ , hypotheses=UpperCAmelCase_ , min_len=UpperCAmelCase_ , max_len=UpperCAmelCase_ ) }
62
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : int = ArgumentParser( description=( "PyTorch TPU distributed training launch " "helper utility that will spawn up " "multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores" , type=lowercase , default=1 , help="Number of TPU cores to use (1 or 8)." ) # positional parser.add_argument( "training_script" , type=lowercase , help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ) , ) # rest from the training program parser.add_argument("training_script_args" , nargs=lowercase ) return parser.parse_args() def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = parse_args() # Import training_script as a module. SCREAMING_SNAKE_CASE : Optional[Any] = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) SCREAMING_SNAKE_CASE : List[Any] = script_fpath.stem SCREAMING_SNAKE_CASE : List[str] = importlib.import_module(lowercase ) # Patch sys.argv SCREAMING_SNAKE_CASE : List[str] = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
62
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[Any] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : float = 0 ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = row, column SCREAMING_SNAKE_CASE : Optional[Any] = [[default_value for c in range(UpperCAmelCase_ )] for r in range(UpperCAmelCase_ )] def __str__( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = f'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE : Optional[Any] = max(UpperCAmelCase_ , len(str(UpperCAmelCase_ ) ) ) SCREAMING_SNAKE_CASE : Optional[int] = f'''%{max_element_length}s''' # Make string and return def single_line(UpperCAmelCase_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE : Optional[int] = "[" line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(UpperCAmelCase_ ) for row_vector in self.array ) return s def __repr__( self : Dict ): return str(self ) def _A ( self : Optional[int] , UpperCAmelCase_ : tuple[int, int] ): if not (isinstance(UpperCAmelCase_ , (list, tuple) ) and len(UpperCAmelCase_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Any , UpperCAmelCase_ : tuple[int, int] ): assert self.validate_indicies(UpperCAmelCase_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : int , UpperCAmelCase_ : tuple[int, int] , UpperCAmelCase_ : float ): assert self.validate_indicies(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = value def __add__( self : Optional[int] , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE : str = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : Any = self[r, c] + another[r, c] return result def __neg__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Union[str, Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = -self[r, c] return result def __sub__( self : Optional[Any] , UpperCAmelCase_ : Matrix ): return self + (-another) def __mul__( self : Dict , UpperCAmelCase_ : int | float | Matrix ): if isinstance(UpperCAmelCase_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE : Any = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : str = self[r, c] * another return result elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE : Any = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE : List[str] = f'''Unsupported type given for another ({type(UpperCAmelCase_ )})''' raise TypeError(UpperCAmelCase_ ) def _A ( self : int ): SCREAMING_SNAKE_CASE : List[str] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE : List[str] = self[r, c] return result def _A ( self : Union[str, Any] , UpperCAmelCase_ : Matrix , UpperCAmelCase_ : Matrix ): assert isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE : Tuple = v.transpose() SCREAMING_SNAKE_CASE : int = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE : str = 1 print(F'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE : Optional[int] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = 1, 2, -3 SCREAMING_SNAKE_CASE : Tuple = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : int = 4, -2, 5 print(F'''u is {u}''' ) print(F'''v is {v}''' ) print(F'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(F'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase , lowercase )}''' ) def lowerCamelCase__ ( ): """simple docstring""" import doctest doctest.testmod() testa()
62
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class SCREAMING_SNAKE_CASE ( unittest.TestCase , lowerCAmelCase ): '''simple docstring''' def _A ( self : List[Any] ): SCREAMING_SNAKE_CASE : List[str] = load_tool("text-classification" ) self.tool.setup() SCREAMING_SNAKE_CASE : int = load_tool("text-classification" , remote=UpperCAmelCase_ ) def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : str = self.tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(UpperCAmelCase_ , "positive" ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Optional[int] = self.remote_tool("That's quite cool" , ["positive", "negative"] ) self.assertEqual(UpperCAmelCase_ , "positive" ) def _A ( self : Dict ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(UpperCAmelCase_ , "positive" ) def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : Any = self.remote_tool(text="That's quite cool" , labels=["positive", "negative"] ) self.assertEqual(UpperCAmelCase_ , "positive" )
62
import json from typing import List, Optional, Tuple from tokenizers import normalizers from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roformer import RoFormerTokenizer from .tokenization_utils import JiebaPreTokenizer snake_case = logging.get_logger(__name__) snake_case = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} snake_case = { """vocab_file""": { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt""" ), } } snake_case = { """junnyu/roformer_chinese_small""": 1_536, """junnyu/roformer_chinese_base""": 1_536, """junnyu/roformer_chinese_char_small""": 512, """junnyu/roformer_chinese_char_base""": 512, """junnyu/roformer_small_discriminator""": 128, """junnyu/roformer_small_generator""": 128, } snake_case = { """junnyu/roformer_chinese_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_base""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_small""": {"""do_lower_case""": True}, """junnyu/roformer_chinese_char_base""": {"""do_lower_case""": True}, """junnyu/roformer_small_discriminator""": {"""do_lower_case""": True}, """junnyu/roformer_small_generator""": {"""do_lower_case""": True}, } class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Optional[Any] = VOCAB_FILES_NAMES UpperCamelCase_ : int = PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] = PRETRAINED_INIT_CONFIGURATION UpperCamelCase_ : Any = RoFormerTokenizer def __init__( self : Tuple , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : Optional[Any]=True , UpperCAmelCase_ : List[str]="[UNK]" , UpperCAmelCase_ : Any="[SEP]" , UpperCAmelCase_ : Any="[PAD]" , UpperCAmelCase_ : List[str]="[CLS]" , UpperCAmelCase_ : str="[MASK]" , UpperCAmelCase_ : Any=True , UpperCAmelCase_ : Optional[Any]=None , **UpperCAmelCase_ : List[str] , ): super().__init__( UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , do_lower_case=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , tokenize_chinese_chars=UpperCAmelCase_ , strip_accents=UpperCAmelCase_ , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE : int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( pre_tok_state.get("lowercase" , UpperCAmelCase_ ) != do_lower_case or pre_tok_state.get("strip_accents" , UpperCAmelCase_ ) != strip_accents ): SCREAMING_SNAKE_CASE : Optional[Any] = getattr(UpperCAmelCase_ , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : List[str] = strip_accents SCREAMING_SNAKE_CASE : Tuple = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = do_lower_case def __getstate__( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() SCREAMING_SNAKE_CASE : Optional[Any] = BertPreTokenizer() return state def __setstate__( self : Tuple , UpperCAmelCase_ : Union[str, Any] ): SCREAMING_SNAKE_CASE : Dict = d SCREAMING_SNAKE_CASE : Dict = self.__dict__["_tokenizer"].get_vocab() SCREAMING_SNAKE_CASE : Any = PreTokenizer.custom(JiebaPreTokenizer(UpperCAmelCase_ ) ) def _A ( self : str , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE : List[Any] = [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 _A ( self : Tuple , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Optional[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 _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE : Optional[int] = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Tuple , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Any=False , **UpperCAmelCase_ : str , ): SCREAMING_SNAKE_CASE : Union[str, Any] = BertPreTokenizer() return super().save_pretrained(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , **UpperCAmelCase_ )
62
1
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml snake_case = NewType("""DataClass""", Any) snake_case = NewType("""DataClassType""", Any) def lowerCamelCase__ ( lowercase ): """simple docstring""" if isinstance(lowercase , lowercase ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = {str(lowercase ): choice for choice in choices} return lambda lowercase : str_to_choice.get(lowercase , lowercase ) def lowerCamelCase__ ( *, lowercase = None , lowercase = None , lowercase = dataclasses.MISSING , lowercase = dataclasses.MISSING , lowercase = None , **lowercase , ): """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls SCREAMING_SNAKE_CASE : Optional[Any] = {} if aliases is not None: SCREAMING_SNAKE_CASE : Optional[Any] = aliases if help is not None: SCREAMING_SNAKE_CASE : Tuple = help return dataclasses.field(metadata=lowercase , default=lowercase , default_factory=lowercase , **lowercase ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase ): '''simple docstring''' UpperCamelCase_ : Iterable[DataClassType] def __init__( self : Optional[int] , UpperCAmelCase_ : Union[DataClassType, Iterable[DataClassType]] , **UpperCAmelCase_ : Optional[int] ): # To make the default appear when using --help if "formatter_class" not in kwargs: SCREAMING_SNAKE_CASE : Optional[int] = ArgumentDefaultsHelpFormatter super().__init__(**UpperCAmelCase_ ) if dataclasses.is_dataclass(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[Any] = [dataclass_types] SCREAMING_SNAKE_CASE : Optional[int] = list(UpperCAmelCase_ ) for dtype in self.dataclass_types: self._add_dataclass_arguments(UpperCAmelCase_ ) @staticmethod def _A ( UpperCAmelCase_ : ArgumentParser , UpperCAmelCase_ : dataclasses.Field ): SCREAMING_SNAKE_CASE : Any = f'''--{field.name}''' SCREAMING_SNAKE_CASE : Tuple = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type , UpperCAmelCase_ ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) SCREAMING_SNAKE_CASE : List[str] = kwargs.pop("aliases" , [] ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : str = [aliases] SCREAMING_SNAKE_CASE : Dict = getattr(field.type , "__origin__" , field.type ) if origin_type is Union or (hasattr(UpperCAmelCase_ , "UnionType" ) and isinstance(UpperCAmelCase_ , types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(UpperCAmelCase_ ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(UpperCAmelCase_ ) not in field.type.__args__: # filter `str` in Union SCREAMING_SNAKE_CASE : List[str] = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] SCREAMING_SNAKE_CASE : Tuple = getattr(field.type , "__origin__" , field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) SCREAMING_SNAKE_CASE : Dict = ( field.type.__args__[0] if isinstance(UpperCAmelCase_ , field.type.__args__[1] ) else field.type.__args__[1] ) SCREAMING_SNAKE_CASE : Optional[Any] = getattr(field.type , "__origin__" , field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) SCREAMING_SNAKE_CASE : Dict = {} if origin_type is Literal or (isinstance(field.type , UpperCAmelCase_ ) and issubclass(field.type , UpperCAmelCase_ )): if origin_type is Literal: SCREAMING_SNAKE_CASE : Any = field.type.__args__ else: SCREAMING_SNAKE_CASE : Union[str, Any] = [x.value for x in field.type] SCREAMING_SNAKE_CASE : Tuple = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: SCREAMING_SNAKE_CASE : Any = field.default else: SCREAMING_SNAKE_CASE : str = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument SCREAMING_SNAKE_CASE : List[str] = copy(UpperCAmelCase_ ) # Hack because type=bool in argparse does not behave as we want. SCREAMING_SNAKE_CASE : Any = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. SCREAMING_SNAKE_CASE : str = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way SCREAMING_SNAKE_CASE : Optional[int] = default # This tells argparse we accept 0 or 1 value after --field_name SCREAMING_SNAKE_CASE : Tuple = "?" # This is the value that will get picked if we do --field_name (without value) SCREAMING_SNAKE_CASE : List[Any] = True elif isclass(UpperCAmelCase_ ) and issubclass(UpperCAmelCase_ , UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : List[str] = field.type.__args__[0] SCREAMING_SNAKE_CASE : List[str] = "+" if field.default_factory is not dataclasses.MISSING: SCREAMING_SNAKE_CASE : Any = field.default_factory() elif field.default is dataclasses.MISSING: SCREAMING_SNAKE_CASE : Optional[int] = True else: SCREAMING_SNAKE_CASE : Optional[Any] = field.type if field.default is not dataclasses.MISSING: SCREAMING_SNAKE_CASE : str = field.default elif field.default_factory is not dataclasses.MISSING: SCREAMING_SNAKE_CASE : Union[str, Any] = field.default_factory() else: SCREAMING_SNAKE_CASE : Tuple = True parser.add_argument(UpperCAmelCase_ , *UpperCAmelCase_ , **UpperCAmelCase_ ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): SCREAMING_SNAKE_CASE : Tuple = False parser.add_argument(f'''--no_{field.name}''' , action="store_false" , dest=field.name , **UpperCAmelCase_ ) def _A ( self : int , UpperCAmelCase_ : DataClassType ): if hasattr(UpperCAmelCase_ , "_argument_group_name" ): SCREAMING_SNAKE_CASE : Tuple = self.add_argument_group(dtype._argument_group_name ) else: SCREAMING_SNAKE_CASE : Dict = self try: SCREAMING_SNAKE_CASE : Dict[str, type] = get_type_hints(UpperCAmelCase_ ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(UpperCAmelCase_ ): SCREAMING_SNAKE_CASE : Union[str, Any] = ".".join(map(UpperCAmelCase_ , sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(UpperCAmelCase_ ): if not field.init: continue SCREAMING_SNAKE_CASE : Tuple = type_hints[field.name] self._parse_dataclass_field(UpperCAmelCase_ , UpperCAmelCase_ ) def _A ( self : List[Any] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[Any]=False , UpperCAmelCase_ : str=True , UpperCAmelCase_ : Any=None , UpperCAmelCase_ : str=None , ): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): SCREAMING_SNAKE_CASE : Tuple = [] if args_filename: args_files.append(Path(UpperCAmelCase_ ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values SCREAMING_SNAKE_CASE : Dict = ArgumentParser() args_file_parser.add_argument(UpperCAmelCase_ , type=UpperCAmelCase_ , action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Any = args_file_parser.parse_known_args(args=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = vars(UpperCAmelCase_ ).get(args_file_flag.lstrip("-" ) , UpperCAmelCase_ ) if cmd_args_file_paths: args_files.extend([Path(UpperCAmelCase_ ) for p in cmd_args_file_paths] ) SCREAMING_SNAKE_CASE : Union[str, Any] = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last SCREAMING_SNAKE_CASE : Any = file_args + args if args is not None else file_args + sys.argv[1:] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = self.parse_known_args(args=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = [] for dtype in self.dataclass_types: SCREAMING_SNAKE_CASE : Tuple = {f.name for f in dataclasses.fields(UpperCAmelCase_ ) if f.init} SCREAMING_SNAKE_CASE : Dict = {k: v for k, v in vars(UpperCAmelCase_ ).items() if k in keys} for k in keys: delattr(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = dtype(**UpperCAmelCase_ ) outputs.append(UpperCAmelCase_ ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(UpperCAmelCase_ ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def _A ( self : Optional[Any] , UpperCAmelCase_ : Dict[str, Any] , UpperCAmelCase_ : bool = False ): SCREAMING_SNAKE_CASE : Tuple = set(args.keys() ) SCREAMING_SNAKE_CASE : Tuple = [] for dtype in self.dataclass_types: SCREAMING_SNAKE_CASE : Optional[Any] = {f.name for f in dataclasses.fields(UpperCAmelCase_ ) if f.init} SCREAMING_SNAKE_CASE : Dict = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) SCREAMING_SNAKE_CASE : Tuple = dtype(**UpperCAmelCase_ ) outputs.append(UpperCAmelCase_ ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(UpperCAmelCase_ )}''' ) return tuple(UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False ): with open(Path(UpperCAmelCase_ ) , encoding="utf-8" ) as open_json_file: SCREAMING_SNAKE_CASE : Dict = json.loads(open_json_file.read() ) SCREAMING_SNAKE_CASE : Dict = self.parse_dict(UpperCAmelCase_ , allow_extra_keys=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def _A ( self : Optional[int] , UpperCAmelCase_ : str , UpperCAmelCase_ : bool = False ): SCREAMING_SNAKE_CASE : Any = self.parse_dict(yaml.safe_load(Path(UpperCAmelCase_ ).read_text() ) , allow_extra_keys=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
62
def lowerCamelCase__ ( lowercase ): """simple docstring""" if not isinstance(lowercase , lowercase ): raise TypeError("only integers accepted as input" ) else: SCREAMING_SNAKE_CASE : Optional[int] = str(abs(lowercase ) ) SCREAMING_SNAKE_CASE : str = [list(lowercase ) for char in range(len(lowercase ) )] for index in range(len(lowercase ) ): num_transpositions[index].pop(lowercase ) return max( int("".join(list(lowercase ) ) ) for transposition in num_transpositions ) if __name__ == "__main__": __import__("""doctest""").testmod()
62
1
import gc import inspect import unittest import torch from parameterized import parameterized from diffusers import PriorTransformer from diffusers.utils import floats_tensor, slow, torch_all_close, torch_device from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = PriorTransformer UpperCamelCase_ : Union[str, Any] = '''hidden_states''' @property def _A ( self : Dict ): SCREAMING_SNAKE_CASE : List[str] = 4 SCREAMING_SNAKE_CASE : Dict = 8 SCREAMING_SNAKE_CASE : List[str] = 7 SCREAMING_SNAKE_CASE : str = floats_tensor((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = floats_tensor((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _A ( self : Optional[Any] , UpperCAmelCase_ : Tuple=0 ): torch.manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = 4 SCREAMING_SNAKE_CASE : int = 8 SCREAMING_SNAKE_CASE : Union[str, Any] = 7 SCREAMING_SNAKE_CASE : int = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } @property def _A ( self : Optional[Any] ): return (4, 8) @property def _A ( self : Any ): return (4, 8) def _A ( self : int ): SCREAMING_SNAKE_CASE : Optional[int] = { "num_attention_heads": 2, "attention_head_dim": 4, "num_layers": 2, "embedding_dim": 8, "num_embeddings": 7, "additional_embeddings": 4, } SCREAMING_SNAKE_CASE : Dict = self.dummy_input return init_dict, inputs_dict def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = PriorTransformer.from_pretrained( "hf-internal-testing/prior-dummy" , output_loading_info=UpperCAmelCase_ ) self.assertIsNotNone(UpperCAmelCase_ ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = model(**self.dummy_input )[0] assert hidden_states is not None, "Make sure output is not None" def _A ( self : Any ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_init_args_and_inputs_for_common() SCREAMING_SNAKE_CASE : Tuple = self.model_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE : Dict = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE : List[Any] = ["hidden_states", "timestep"] self.assertListEqual(arg_names[:2] , UpperCAmelCase_ ) def _A ( self : Optional[int] ): SCREAMING_SNAKE_CASE : Dict = PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" ) SCREAMING_SNAKE_CASE : str = model.to(UpperCAmelCase_ ) if hasattr(UpperCAmelCase_ , "set_default_attn_processor" ): model.set_default_attn_processor() SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_seed_input() with torch.no_grad(): SCREAMING_SNAKE_CASE : List[Any] = model(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = output[0, :5].flatten().cpu() print(UpperCAmelCase_ ) # 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. SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([-1.3_436, -0.2_870, 0.7_538, 0.4_368, -0.0_239] ) self.assertTrue(torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , rtol=1E-2 ) ) @slow class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : str , UpperCAmelCase_ : Dict=1 , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : List[str]=77 , UpperCAmelCase_ : List[Any]=0 ): torch.manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = batch_size SCREAMING_SNAKE_CASE : int = embedding_dim SCREAMING_SNAKE_CASE : Optional[Any] = num_embeddings SCREAMING_SNAKE_CASE : Tuple = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.randn((batch_size, embedding_dim) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = torch.randn((batch_size, num_embeddings, embedding_dim) ).to(UpperCAmelCase_ ) return { "hidden_states": hidden_states, "timestep": 2, "proj_embedding": proj_embedding, "encoder_hidden_states": encoder_hidden_states, } def _A ( self : int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @parameterized.expand( [ # fmt: off [13, [-0.5_861, 0.1_283, -0.0_931, 0.0_882, 0.4_476, 0.1_329, -0.0_498, 0.0_640]], [37, [-0.4_913, 0.0_110, -0.0_483, 0.0_541, 0.4_954, -0.0_170, 0.0_354, 0.1_651]], # fmt: on ] ) def _A ( self : List[Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : List[str] ): SCREAMING_SNAKE_CASE : int = PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior" , subfolder="prior" ) model.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_seed_input(seed=UpperCAmelCase_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE : str = model(**UpperCAmelCase_ )[0] assert list(sample.shape ) == [1, 768] SCREAMING_SNAKE_CASE : Optional[int] = sample[0, :8].flatten().cpu() print(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(UpperCAmelCase_ ) assert torch_all_close(UpperCAmelCase_ , UpperCAmelCase_ , atol=1E-3 )
62
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : int = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({'''control_image'''} ) UpperCamelCase_ : Any = IMAGE_TO_IMAGE_IMAGE_PARAMS def _A ( self : List[str] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : str = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : str , UpperCAmelCase_ : List[str] , UpperCAmelCase_ : int=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Any = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = 2 SCREAMING_SNAKE_CASE : Union[str, Any] = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ) SCREAMING_SNAKE_CASE : Tuple = floats_tensor(control_image.shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : str = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : List[str] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : int ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : Union[str, Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class SCREAMING_SNAKE_CASE ( lowerCAmelCase , lowerCAmelCase , unittest.TestCase ): '''simple docstring''' UpperCamelCase_ : List[str] = StableDiffusionControlNetImgaImgPipeline UpperCamelCase_ : str = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''} UpperCamelCase_ : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase_ : Dict = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def _A ( self : Optional[Any] ): torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(UpperCAmelCase_ : List[Any] ): if isinstance(UpperCAmelCase_ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) SCREAMING_SNAKE_CASE : List[str] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(UpperCAmelCase_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=UpperCAmelCase_ , set_alpha_to_one=UpperCAmelCase_ , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE : Any = CLIPTextModel(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) SCREAMING_SNAKE_CASE : Tuple = MultiControlNetModel([controlneta, controlneta] ) SCREAMING_SNAKE_CASE : Optional[int] = { "unet": unet, "controlnet": controlnet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def _A ( self : List[str] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Any=0 ): if str(UpperCAmelCase_ ).startswith("mps" ): SCREAMING_SNAKE_CASE : Dict = torch.manual_seed(UpperCAmelCase_ ) else: SCREAMING_SNAKE_CASE : str = torch.Generator(device=UpperCAmelCase_ ).manual_seed(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Any = 2 SCREAMING_SNAKE_CASE : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=UpperCAmelCase_ , device=torch.device(UpperCAmelCase_ ) , ), ] SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor(control_image[0].shape , rng=random.Random(UpperCAmelCase_ ) ).to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = Image.fromarray(np.uinta(UpperCAmelCase_ ) ).convert("RGB" ).resize((64, 64) ) SCREAMING_SNAKE_CASE : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", "image": image, "control_image": control_image, } return inputs def _A ( self : Tuple ): SCREAMING_SNAKE_CASE : Any = self.get_dummy_components() SCREAMING_SNAKE_CASE : str = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = 10.0 SCREAMING_SNAKE_CASE : Any = 4 SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : Optional[int] = pipe(**UpperCAmelCase_ )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = steps SCREAMING_SNAKE_CASE : Any = scale SCREAMING_SNAKE_CASE : List[str] = pipe(**UpperCAmelCase_ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = steps SCREAMING_SNAKE_CASE : int = scale SCREAMING_SNAKE_CASE : List[Any] = pipe(**UpperCAmelCase_ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_inputs(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = steps SCREAMING_SNAKE_CASE : Dict = scale SCREAMING_SNAKE_CASE : Dict = pipe(**UpperCAmelCase_ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def _A ( self : Union[str, Any] ): return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _A ( self : str ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def _A ( self : List[Any] ): self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def _A ( self : Any ): SCREAMING_SNAKE_CASE : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE : Dict = self.pipeline_class(**UpperCAmelCase_ ) pipe.to(UpperCAmelCase_ ) pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(UpperCAmelCase_ ) except NotImplementedError: pass @slow @require_torch_gpu class SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' def _A ( self : Optional[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self : Optional[Any] ): SCREAMING_SNAKE_CASE : str = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny" ) SCREAMING_SNAKE_CASE : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline.from_pretrained( "runwayml/stable-diffusion-v1-5" , safety_checker=UpperCAmelCase_ , controlnet=UpperCAmelCase_ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = "evil space-punk bird" SCREAMING_SNAKE_CASE : Optional[Any] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png" ).resize((512, 512) ) SCREAMING_SNAKE_CASE : str = pipe( UpperCAmelCase_ , UpperCAmelCase_ , control_image=UpperCAmelCase_ , generator=UpperCAmelCase_ , output_type="np" , num_inference_steps=50 , strength=0.6 , ) SCREAMING_SNAKE_CASE : int = output.images[0] assert image.shape == (512, 512, 3) SCREAMING_SNAKE_CASE : Dict = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy" ) assert np.abs(expected_image - image ).max() < 9E-2
62
1
from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean snake_case = 0 snake_case = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] snake_case = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right snake_case = tuple[int, int] class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Optional[int] , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : Node | None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = pos_x SCREAMING_SNAKE_CASE : Any = pos_y SCREAMING_SNAKE_CASE : Optional[Any] = (pos_y, pos_x) SCREAMING_SNAKE_CASE : Any = goal_x SCREAMING_SNAKE_CASE : Optional[Any] = goal_y SCREAMING_SNAKE_CASE : Dict = g_cost SCREAMING_SNAKE_CASE : int = parent SCREAMING_SNAKE_CASE : int = self.calculate_heuristic() SCREAMING_SNAKE_CASE : List[Any] = self.g_cost + self.h_cost def _A ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE : Optional[int] = self.pos_x - self.goal_x SCREAMING_SNAKE_CASE : Optional[int] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(UpperCAmelCase_ ) + abs(UpperCAmelCase_ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : Union[str, Any] , UpperCAmelCase_ : Node ): return self.f_cost < other.f_cost class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : Union[str, Any] , UpperCAmelCase_ : TPosition , UpperCAmelCase_ : TPosition ): SCREAMING_SNAKE_CASE : List[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Optional[int] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9999 , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = [self.start] SCREAMING_SNAKE_CASE : list[Node] = [] SCREAMING_SNAKE_CASE : Tuple = False def _A ( self : Union[str, Any] ): while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() SCREAMING_SNAKE_CASE : List[Any] = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(UpperCAmelCase_ ) self.closed_nodes.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = self.get_successors(UpperCAmelCase_ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(UpperCAmelCase_ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE : Union[str, Any] = self.open_nodes.pop(self.open_nodes.index(UpperCAmelCase_ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(UpperCAmelCase_ ) else: self.open_nodes.append(UpperCAmelCase_ ) return [self.start.pos] def _A ( self : List[Any] , UpperCAmelCase_ : Node ): SCREAMING_SNAKE_CASE : int = [] for action in delta: SCREAMING_SNAKE_CASE : Optional[Any] = parent.pos_x + action[1] SCREAMING_SNAKE_CASE : Any = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(UpperCAmelCase_ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( UpperCAmelCase_ , UpperCAmelCase_ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , UpperCAmelCase_ , ) ) return successors def _A ( self : str , UpperCAmelCase_ : Node | None ): SCREAMING_SNAKE_CASE : List[Any] = node SCREAMING_SNAKE_CASE : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) SCREAMING_SNAKE_CASE : Optional[int] = current_node.parent path.reverse() return path class SCREAMING_SNAKE_CASE : '''simple docstring''' def __init__( self : List[str] , UpperCAmelCase_ : TPosition , UpperCAmelCase_ : TPosition ): SCREAMING_SNAKE_CASE : List[str] = AStar(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : int = AStar(UpperCAmelCase_ , UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : str = False def _A ( self : List[Any] ): while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() SCREAMING_SNAKE_CASE : Optional[int] = self.fwd_astar.open_nodes.pop(0 ) SCREAMING_SNAKE_CASE : Dict = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( UpperCAmelCase_ , UpperCAmelCase_ ) self.fwd_astar.closed_nodes.append(UpperCAmelCase_ ) self.bwd_astar.closed_nodes.append(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : Tuple = current_bwd_node SCREAMING_SNAKE_CASE : Tuple = current_fwd_node SCREAMING_SNAKE_CASE : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(UpperCAmelCase_ ), self.bwd_astar: self.bwd_astar.get_successors(UpperCAmelCase_ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(UpperCAmelCase_ ) else: # retrieve the best current path SCREAMING_SNAKE_CASE : Optional[int] = astar.open_nodes.pop( astar.open_nodes.index(UpperCAmelCase_ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(UpperCAmelCase_ ) else: astar.open_nodes.append(UpperCAmelCase_ ) return [self.fwd_astar.start.pos] def _A ( self : Any , UpperCAmelCase_ : Node , UpperCAmelCase_ : Node ): SCREAMING_SNAKE_CASE : str = self.fwd_astar.retrace_path(UpperCAmelCase_ ) SCREAMING_SNAKE_CASE : List[str] = self.bwd_astar.retrace_path(UpperCAmelCase_ ) bwd_path.pop() bwd_path.reverse() SCREAMING_SNAKE_CASE : List[Any] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] snake_case = (0, 0) snake_case = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) snake_case = time.time() snake_case = AStar(init, goal) snake_case = a_star.search() snake_case = time.time() - start_time print(F"""AStar execution time = {end_time:f} seconds""") snake_case = time.time() snake_case = BidirectionalAStar(init, goal) snake_case = time.time() - bd_start_time print(F"""BidirectionalAStar execution time = {bd_end_time:f} seconds""")
62
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case = logging.get_logger(__name__) def lowerCamelCase__ ( lowercase ): """simple docstring""" SCREAMING_SNAKE_CASE : int = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: SCREAMING_SNAKE_CASE : List[Any] = [144, 192, 240] SCREAMING_SNAKE_CASE : Tuple = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [96, 120, 144] SCREAMING_SNAKE_CASE : Dict = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: SCREAMING_SNAKE_CASE : List[str] = [64, 80, 96] SCREAMING_SNAKE_CASE : List[str] = [16, 16, 24, 48, 64, 80, 320] SCREAMING_SNAKE_CASE : int = 0.05 SCREAMING_SNAKE_CASE : int = 2.0 if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : str = 512 SCREAMING_SNAKE_CASE : List[str] = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 21 SCREAMING_SNAKE_CASE : Dict = "pascal-voc-id2label.json" else: SCREAMING_SNAKE_CASE : Optional[Any] = 1000 SCREAMING_SNAKE_CASE : Optional[Any] = "imagenet-1k-id2label.json" SCREAMING_SNAKE_CASE : Any = "huggingface/label-files" SCREAMING_SNAKE_CASE : Tuple = json.load(open(hf_hub_download(lowercase , lowercase , repo_type="dataset" ) , "r" ) ) SCREAMING_SNAKE_CASE : List[str] = {int(lowercase ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : Optional[Any] = idalabel SCREAMING_SNAKE_CASE : str = {v: k for k, v in idalabel.items()} return config def lowerCamelCase__ ( lowercase , lowercase=False ): """simple docstring""" for i in range(1 , 6 ): if F'''layer_{i}.''' in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(F'''layer_{i}.''' , F'''encoder.layer.{i - 1}.''' ) if "conv_1." in name: SCREAMING_SNAKE_CASE : Dict = name.replace("conv_1." , "conv_stem." ) if ".block." in name: SCREAMING_SNAKE_CASE : List[str] = name.replace(".block." , "." ) if "exp_1x1" in name: SCREAMING_SNAKE_CASE : str = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: SCREAMING_SNAKE_CASE : int = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".norm." , ".normalization." ) if ".conv." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.layer.{j}.''' ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F'''.{i}.{j}.''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.{i}.{j}.''' , F'''.{i}.''' ) if "expand_1x1" in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: SCREAMING_SNAKE_CASE : str = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F'''.global_rep.{i}.weight''' in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace(F'''.global_rep.{i}.weight''' , ".layernorm.weight" ) if F'''.global_rep.{i}.bias''' in name: SCREAMING_SNAKE_CASE : str = name.replace(F'''.global_rep.{i}.bias''' , ".layernorm.bias" ) if ".global_rep." in name: SCREAMING_SNAKE_CASE : Dict = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: SCREAMING_SNAKE_CASE : Union[str, Any] = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: SCREAMING_SNAKE_CASE : int = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: SCREAMING_SNAKE_CASE : Tuple = name.replace(".aspp_pool." , "." ) if "seg_head." in name: SCREAMING_SNAKE_CASE : Optional[int] = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: SCREAMING_SNAKE_CASE : Optional[Any] = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: SCREAMING_SNAKE_CASE : List[Any] = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): SCREAMING_SNAKE_CASE : List[Any] = "mobilevit." + name return name def lowerCamelCase__ ( lowercase , lowercase , lowercase=False ): """simple docstring""" if base_model: SCREAMING_SNAKE_CASE : Optional[int] = "" else: SCREAMING_SNAKE_CASE : Any = "mobilevit." for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE : Union[str, Any] = orig_state_dict.pop(lowercase ) if key[:8] == "encoder.": SCREAMING_SNAKE_CASE : int = key[8:] if "qkv" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.split("." ) SCREAMING_SNAKE_CASE : Any = int(key_split[0][6:] ) - 1 SCREAMING_SNAKE_CASE : List[Any] = int(key_split[3] ) SCREAMING_SNAKE_CASE : List[Any] = model.get_submodule(F'''{model_prefix}encoder.layer.{layer_num}''' ) SCREAMING_SNAKE_CASE : int = layer.transformer.layer[transformer_num].attention.attention.all_head_size SCREAMING_SNAKE_CASE : Union[str, Any] = ( F'''{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.''' ) if "weight" in key: SCREAMING_SNAKE_CASE : Optional[int] = val[:dim, :] SCREAMING_SNAKE_CASE : Tuple = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE : Dict = val[-dim:, :] else: SCREAMING_SNAKE_CASE : str = val[:dim] SCREAMING_SNAKE_CASE : Union[str, Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE : List[Any] = val return orig_state_dict def lowerCamelCase__ ( ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(lowercase , stream=lowercase ).raw ) return im @torch.no_grad() def lowerCamelCase__ ( lowercase , lowercase , lowercase , lowercase=False ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_mobilevit_config(lowercase ) # load original state_dict SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(lowercase , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): SCREAMING_SNAKE_CASE : List[str] = MobileViTForSemanticSegmentation(lowercase ).eval() else: SCREAMING_SNAKE_CASE : str = MobileViTForImageClassification(lowercase ).eval() SCREAMING_SNAKE_CASE : Any = convert_state_dict(lowercase , lowercase ) model.load_state_dict(lowercase ) # Check outputs on an image, prepared by MobileViTImageProcessor SCREAMING_SNAKE_CASE : List[Any] = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) SCREAMING_SNAKE_CASE : Union[str, Any] = image_processor(images=prepare_img() , return_tensors="pt" ) SCREAMING_SNAKE_CASE : List[Any] = model(**lowercase ) SCREAMING_SNAKE_CASE : str = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [ [[6.2065, 6.1292, 6.2070], [6.1079, 6.1254, 6.1747], [6.0042, 6.1071, 6.1034]], [[-6.9253, -6.8653, -7.0398], [-7.3218, -7.3983, -7.3670], [-7.1961, -7.2482, -7.1569]], [[-4.4723, -4.4348, -4.3769], [-5.3629, -5.4632, -5.4598], [-5.1587, -5.3402, -5.5059]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor( [ [[5.4449, 5.5733, 5.6314], [5.1815, 5.3930, 5.5963], [5.1656, 5.4333, 5.4853]], [[-9.4423, -9.7766, -9.6714], [-9.1581, -9.5720, -9.5519], [-9.1006, -9.6458, -9.5703]], [[-7.7721, -7.3716, -7.1583], [-8.4599, -8.0624, -7.7944], [-8.4172, -7.8366, -7.5025]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor( [ [[6.9811, 6.9743, 7.3123], [7.1777, 7.1931, 7.3938], [7.5633, 7.8050, 7.8901]], [[-10.5536, -10.2332, -10.2924], [-10.2336, -9.8624, -9.5964], [-10.8840, -10.8158, -10.6659]], [[-3.4938, -3.0631, -2.8620], [-3.4205, -2.8135, -2.6875], [-3.4179, -2.7945, -2.8750]], ] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3, :3, :3] , lowercase , atol=1E-4 ) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([-0.9866, 0.2392, -1.1241] ) elif mobilevit_name == "mobilevit_xs": SCREAMING_SNAKE_CASE : Dict = torch.tensor([-2.4761, -0.9399, -1.9587] ) elif mobilevit_name == "mobilevit_xxs": SCREAMING_SNAKE_CASE : Tuple = torch.tensor([-1.9364, -1.2327, -0.4653] ) else: raise ValueError(F'''Unknown mobilevit_name: {mobilevit_name}''' ) assert torch.allclose(logits[0, :3] , lowercase , atol=1E-4 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'''Saving model {mobilevit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase ) if push_to_hub: SCREAMING_SNAKE_CASE : List[str] = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) SCREAMING_SNAKE_CASE : int = model_mapping[mobilevit_name] image_processor.push_to_hub(lowercase , organization="apple" ) model.push_to_hub(lowercase , organization="apple" ) if __name__ == "__main__": snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) snake_case = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
62
1