code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import os from pathlib import Path def lowerCAmelCase__ ( ) -> Optional[int]: '''simple docstring''' from torch.utils.cpp_extension import load _UpperCAmelCase = Path(a__ ).resolve().parent.parent.parent / 'kernels' / 'deformable_detr' _UpperCAmelCase = [ root / filename for filename in [ 'vision.cpp', os.path.join('cpu' , 'ms_deform_attn_cpu.cpp' ), os.path.join('cuda' , 'ms_deform_attn_cuda.cu' ), ] ] load( 'MultiScaleDeformableAttention' , a__ , with_cuda=a__ , extra_include_paths=[str(a__ )] , extra_cflags=['-DWITH_CUDA=1'] , extra_cuda_cflags=[ '-DCUDA_HAS_FP16=1', '-D__CUDA_NO_HALF_OPERATORS__', '-D__CUDA_NO_HALF_CONVERSIONS__', '-D__CUDA_NO_HALF2_OPERATORS__', ] , ) import MultiScaleDeformableAttention as MSDA return MSDA
329
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
1
from __future__ import annotations from typing import Any class __a ( UpperCAmelCase ): pass class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = data _UpperCAmelCase = None def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self _UpperCAmelCase = [] while node: if node in visited: raise ContainsLoopError visited.append(_SCREAMING_SNAKE_CASE ) yield node.data _UpperCAmelCase = node.next_node @property def UpperCAmelCase__ ( self ) -> bool: """simple docstring""" try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": lowerCAmelCase__ :Optional[int] = Node(1) lowerCAmelCase__ :Dict = Node(2) lowerCAmelCase__ :Union[str, Any] = Node(3) lowerCAmelCase__ :Union[str, Any] = Node(4) print(root_node.has_loop) # False lowerCAmelCase__ :str = root_node.next_node print(root_node.has_loop) # True lowerCAmelCase__ :Any = Node(5) lowerCAmelCase__ :Optional[int] = Node(6) lowerCAmelCase__ :Optional[Any] = Node(5) lowerCAmelCase__ :Optional[Any] = Node(6) print(root_node.has_loop) # False lowerCAmelCase__ :str = Node(1) print(root_node.has_loop) # False
329
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 20} _UpperCAmelCase = do_thumbnail _UpperCAmelCase = do_align_axis _UpperCAmelCase = do_pad _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = DonutImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DonutImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 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 , 'do_thumbnail' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_align_long_axis' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , )
329
1
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase__ :Optional[int] = logging.get_logger(__name__) lowerCAmelCase__ :List[str] = { '''microsoft/focalnet-tiny''': '''https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json''', } class __a ( UpperCAmelCase , UpperCAmelCase ): _a : List[Any] = 'focalnet' def __init__( self , _SCREAMING_SNAKE_CASE=224 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=96 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=[192, 384, 768, 768] , _SCREAMING_SNAKE_CASE=[2, 2, 6, 2] , _SCREAMING_SNAKE_CASE=[2, 2, 2, 2] , _SCREAMING_SNAKE_CASE=[3, 3, 3, 3] , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=4.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=1e-4 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> Optional[int]: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = use_conv_embed _UpperCAmelCase = hidden_sizes _UpperCAmelCase = depths _UpperCAmelCase = focal_levels _UpperCAmelCase = focal_windows _UpperCAmelCase = hidden_act _UpperCAmelCase = mlp_ratio _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = use_layerscale _UpperCAmelCase = layerscale_value _UpperCAmelCase = use_post_layernorm _UpperCAmelCase = use_post_layernorm_in_modulation _UpperCAmelCase = normalize_modulator _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = encoder_stride _UpperCAmelCase = ['stem'] + [f'''stage{idx}''' for idx in range(1 , len(self.depths ) + 1 )] _UpperCAmelCase , _UpperCAmelCase = get_aligned_output_features_output_indices( out_features=_SCREAMING_SNAKE_CASE , out_indices=_SCREAMING_SNAKE_CASE , stage_names=self.stage_names )
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import argparse import torch from huggingface_hub import hf_hub_download from transformers import AutoTokenizer, RobertaPreLayerNormConfig, RobertaPreLayerNormForMaskedLM from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :str = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: str , a__: str ) -> Dict: '''simple docstring''' _UpperCAmelCase = RobertaPreLayerNormConfig.from_pretrained( a__ , architectures=['RobertaPreLayerNormForMaskedLM'] ) # convert state_dict _UpperCAmelCase = torch.load(hf_hub_download(repo_id=a__ , filename='pytorch_model.bin' ) ) _UpperCAmelCase = {} for tensor_key, tensor_value in original_state_dict.items(): # The transformer implementation gives the model a unique name, rather than overwiriting 'roberta' if tensor_key.startswith('roberta.' ): _UpperCAmelCase = 'roberta_prelayernorm.' + tensor_key[len('roberta.' ) :] # The original implementation contains weights which are not used, remove them from the state_dict if tensor_key.endswith('.self.LayerNorm.weight' ) or tensor_key.endswith('.self.LayerNorm.bias' ): continue _UpperCAmelCase = tensor_value _UpperCAmelCase = RobertaPreLayerNormForMaskedLM.from_pretrained( pretrained_model_name_or_path=a__ , config=a__ , state_dict=a__ ) model.save_pretrained(a__ ) # convert tokenizer _UpperCAmelCase = AutoTokenizer.from_pretrained(a__ ) tokenizer.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint-repo''', default=None, type=str, required=True, help='''Path the official PyTorch dump, e.g. \'andreasmadsen/efficient_mlm_m0.40\'.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_roberta_prelayernorm_checkpoint_to_pytorch(args.checkpoint_repo, args.pytorch_dump_folder_path)
329
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
1
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowerCAmelCase__ :Union[str, Any] = TypeVar('''T''') def lowerCAmelCase__ ( a__: int ) -> int: '''simple docstring''' return (position - 1) // 2 def lowerCAmelCase__ ( a__: int ) -> int: '''simple docstring''' return (2 * position) + 1 def lowerCAmelCase__ ( a__: int ) -> int: '''simple docstring''' return (2 * position) + 2 class __a ( Generic[T] ): def __init__( self ) -> None: """simple docstring""" _UpperCAmelCase = [] _UpperCAmelCase = {} _UpperCAmelCase = 0 def __len__( self ) -> int: """simple docstring""" return self.elements def __repr__( self ) -> str: """simple docstring""" return str(self.heap ) def UpperCAmelCase__ ( self ) -> bool: """simple docstring""" return self.elements == 0 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" self.heap.append((elem, weight) ) _UpperCAmelCase = self.elements self.elements += 1 self._bubble_up(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> T: """simple docstring""" if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) _UpperCAmelCase , _UpperCAmelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: _UpperCAmelCase , _UpperCAmelCase = self.heap[0] self._bubble_down(_SCREAMING_SNAKE_CASE ) return elem def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.position_map[elem] _UpperCAmelCase = (elem, weight) if position > 0: _UpperCAmelCase = get_parent_position(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_SCREAMING_SNAKE_CASE ) else: self._bubble_down(_SCREAMING_SNAKE_CASE ) else: self._bubble_down(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.position_map[elem] if curr_pos == 0: return None _UpperCAmelCase = get_parent_position(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = self.heap[curr_pos] _UpperCAmelCase , _UpperCAmelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self._bubble_up(_SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.position_map[elem] _UpperCAmelCase , _UpperCAmelCase = self.heap[curr_pos] _UpperCAmelCase = get_child_left_position(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = get_child_right_position(_SCREAMING_SNAKE_CASE ) if child_left_position < self.elements and child_right_position < self.elements: _UpperCAmelCase , _UpperCAmelCase = self.heap[child_left_position] _UpperCAmelCase , _UpperCAmelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self._bubble_down(_SCREAMING_SNAKE_CASE ) if child_left_position < self.elements: _UpperCAmelCase , _UpperCAmelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self._bubble_down(_SCREAMING_SNAKE_CASE ) else: return None if child_right_position < self.elements: _UpperCAmelCase , _UpperCAmelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return self._bubble_down(_SCREAMING_SNAKE_CASE ) return None def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.heap[nodea_pos][0] _UpperCAmelCase = self.heap[nodea_pos][0] _UpperCAmelCase , _UpperCAmelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) _UpperCAmelCase = nodea_pos _UpperCAmelCase = nodea_pos class __a ( Generic[T] ): def __init__( self ) -> None: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = 0 def __repr__( self ) -> str: """simple docstring""" return str(self.connections ) def __len__( self ) -> int: """simple docstring""" return self.nodes def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" if node not in self.connections: _UpperCAmelCase = {} self.nodes += 1 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" self.add_node(_SCREAMING_SNAKE_CASE ) self.add_node(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = weight _UpperCAmelCase = weight def lowerCAmelCase__ ( a__: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: '''simple docstring''' _UpperCAmelCase = {node: maxsize for node in graph.connections} _UpperCAmelCase = {node: None for node in graph.connections} _UpperCAmelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(a__ , a__ ) if priority_queue.is_empty(): return dist, parent # initialization _UpperCAmelCase = priority_queue.extract_min() _UpperCAmelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: _UpperCAmelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) _UpperCAmelCase = node # running prim's algorithm while not priority_queue.is_empty(): _UpperCAmelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: _UpperCAmelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(a__ , dist[neighbour] ) _UpperCAmelCase = node return dist, parent
329
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
1
def lowerCAmelCase__ ( a__: list[int] , a__: list[int] , a__: int ) -> bool: '''simple docstring''' return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(a__ ) ) def lowerCAmelCase__ ( a__: list[list[int]] , a__: int , a__: list[int] , a__: int ) -> bool: '''simple docstring''' if index == len(a__ ): return True # Recursive Step for i in range(a__ ): if valid_coloring(graph[index] , a__ , a__ ): # Color current vertex _UpperCAmelCase = i # Validate coloring if util_color(a__ , a__ , a__ , index + 1 ): return True # Backtrack _UpperCAmelCase = -1 return False def lowerCAmelCase__ ( a__: list[list[int]] , a__: int ) -> list[int]: '''simple docstring''' _UpperCAmelCase = [-1] * len(a__ ) if util_color(a__ , a__ , a__ , 0 ): return colored_vertices return []
329
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
1
import argparse from collections import OrderedDict from pathlib import Path import requests import torch from PIL import Image from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Optional[int] = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: str ) -> Dict: '''simple docstring''' _UpperCAmelCase = OrderedDict() for key, value in state_dict.items(): if key.startswith('module.encoder' ): _UpperCAmelCase = key.replace('module.encoder' , 'glpn.encoder' ) if key.startswith('module.decoder' ): _UpperCAmelCase = key.replace('module.decoder' , 'decoder.stages' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 _UpperCAmelCase = key[key.find('patch_embed' ) + len('patch_embed' )] _UpperCAmelCase = key.replace(F'''patch_embed{idx}''' , F'''patch_embeddings.{int(a__ )-1}''' ) if "norm" in key: _UpperCAmelCase = key.replace('norm' , 'layer_norm' ) if "glpn.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 _UpperCAmelCase = key[key.find('glpn.encoder.layer_norm' ) + len('glpn.encoder.layer_norm' )] _UpperCAmelCase = key.replace(F'''layer_norm{idx}''' , F'''layer_norm.{int(a__ )-1}''' ) if "layer_norm1" in key: _UpperCAmelCase = key.replace('layer_norm1' , 'layer_norm_1' ) if "layer_norm2" in key: _UpperCAmelCase = key.replace('layer_norm2' , 'layer_norm_2' ) if "block" in key: # replace for example block1 by block.0 _UpperCAmelCase = key[key.find('block' ) + len('block' )] _UpperCAmelCase = key.replace(F'''block{idx}''' , F'''block.{int(a__ )-1}''' ) if "attn.q" in key: _UpperCAmelCase = key.replace('attn.q' , 'attention.self.query' ) if "attn.proj" in key: _UpperCAmelCase = key.replace('attn.proj' , 'attention.output.dense' ) if "attn" in key: _UpperCAmelCase = key.replace('attn' , 'attention.self' ) if "fc1" in key: _UpperCAmelCase = key.replace('fc1' , 'dense1' ) if "fc2" in key: _UpperCAmelCase = key.replace('fc2' , 'dense2' ) if "linear_pred" in key: _UpperCAmelCase = key.replace('linear_pred' , 'classifier' ) if "linear_fuse" in key: _UpperCAmelCase = key.replace('linear_fuse.conv' , 'linear_fuse' ) _UpperCAmelCase = key.replace('linear_fuse.bn' , 'batch_norm' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 _UpperCAmelCase = key[key.find('linear_c' ) + len('linear_c' )] _UpperCAmelCase = key.replace(F'''linear_c{idx}''' , F'''linear_c.{int(a__ )-1}''' ) if "bot_conv" in key: _UpperCAmelCase = key.replace('bot_conv' , '0.convolution' ) if "skip_conv1" in key: _UpperCAmelCase = key.replace('skip_conv1' , '1.convolution' ) if "skip_conv2" in key: _UpperCAmelCase = key.replace('skip_conv2' , '2.convolution' ) if "fusion1" in key: _UpperCAmelCase = key.replace('fusion1' , '1.fusion' ) if "fusion2" in key: _UpperCAmelCase = key.replace('fusion2' , '2.fusion' ) if "fusion3" in key: _UpperCAmelCase = key.replace('fusion3' , '3.fusion' ) if "fusion" in key and "conv" in key: _UpperCAmelCase = key.replace('conv' , 'convolutional_layer' ) if key.startswith('module.last_layer_depth' ): _UpperCAmelCase = key.replace('module.last_layer_depth' , 'head.head' ) _UpperCAmelCase = value return new_state_dict def lowerCAmelCase__ ( a__: Dict , a__: Union[str, Any] ) -> int: '''simple docstring''' for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) _UpperCAmelCase = state_dict.pop(F'''glpn.encoder.block.{i}.{j}.attention.self.kv.weight''' ) _UpperCAmelCase = state_dict.pop(F'''glpn.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict _UpperCAmelCase = kv_weight[ : config.hidden_sizes[i], : ] _UpperCAmelCase = kv_bias[: config.hidden_sizes[i]] _UpperCAmelCase = kv_weight[ config.hidden_sizes[i] :, : ] _UpperCAmelCase = kv_bias[config.hidden_sizes[i] :] def lowerCAmelCase__ ( ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return image @torch.no_grad() def lowerCAmelCase__ ( a__: str , a__: Any , a__: Tuple=False , a__: Optional[int]=None ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase = GLPNConfig(hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2] , decoder_hidden_size=6_4 , depths=[3, 8, 2_7, 3] ) # load image processor (only resize + rescale) _UpperCAmelCase = GLPNImageProcessor() # prepare image _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ).pixel_values logger.info('Converting model...' ) # load original state dict _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) # rename keys _UpperCAmelCase = rename_keys(a__ ) # key and value matrices need special treatment read_in_k_v(a__ , a__ ) # create HuggingFace model and load state dict _UpperCAmelCase = GLPNForDepthEstimation(a__ ) model.load_state_dict(a__ ) model.eval() # forward pass _UpperCAmelCase = model(a__ ) _UpperCAmelCase = outputs.predicted_depth # verify output if model_name is not None: if "nyu" in model_name: _UpperCAmelCase = torch.tensor( [[4.4_147, 4.0_873, 4.0_673], [3.7_890, 3.2_881, 3.1_525], [3.7_674, 3.5_423, 3.4_913]] ) elif "kitti" in model_name: _UpperCAmelCase = torch.tensor( [[3.4_291, 2.7_865, 2.5_151], [3.2_841, 2.7_021, 2.3_502], [3.1_147, 2.4_625, 2.2_481]] ) else: raise ValueError(F'''Unknown model name: {model_name}''' ) _UpperCAmelCase = torch.Size([1, 4_8_0, 6_4_0] ) assert predicted_depth.shape == expected_shape assert torch.allclose(predicted_depth[0, :3, :3] , a__ , atol=1e-4 ) print('Looks ok!' ) # finally, push to hub if required if push_to_hub: logger.info('Pushing model and image processor to the hub...' ) model.push_to_hub( repo_path_or_name=Path(a__ , a__ ) , organization='nielsr' , commit_message='Add model' , use_temp_dir=a__ , ) image_processor.push_to_hub( repo_path_or_name=Path(a__ , a__ ) , organization='nielsr' , commit_message='Add image processor' , use_temp_dir=a__ , ) if __name__ == "__main__": lowerCAmelCase__ :Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether to upload the model to the HuggingFace hub.''' ) parser.add_argument( '''--model_name''', default='''glpn-kitti''', type=str, help='''Name of the model in case you\'re pushing to the hub.''', ) lowerCAmelCase__ :str = parser.parse_args() convert_glpn_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
329
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _UpperCAmelCase = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE , os.listdir(_SCREAMING_SNAKE_CASE )[0] , 'snapshots' ) )] _UpperCAmelCase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 4 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1514745 ) < 1e-3 assert np.abs(np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 49947.875 ) < 5e-1 _UpperCAmelCase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_SCREAMING_SNAKE_CASE ) == num_samples def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05652401) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2383808.2) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = FlaxDDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = scheduler.create_state() _UpperCAmelCase = scheduler_state _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045043945) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2347693.5) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = jax.random.split(jax.random.PRNGKey(0 ) , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # With memory efficient attention _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , use_memory_efficient_attention=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
329
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCAmelCase__ :Union[str, Any] = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :List[str] = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :List[Any] = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :int = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Any = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys lowerCAmelCase__ :Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
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(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ :int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} if prompt is not None: _UpperCAmelCase = prompt if generate_kwargs is not None: _UpperCAmelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _UpperCAmelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,' ' please use only one' ) _UpperCAmelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. ''' 'Note also that one single text can be provided for conditional image to text generation.' ) _UpperCAmelCase = self.model.config.model_type if model_type == "git": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids _UpperCAmelCase = [self.tokenizer.cls_token_id] + input_ids _UpperCAmelCase = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _UpperCAmelCase = None return model_inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs['input_ids'] ) ): _UpperCAmelCase = None if generate_kwargs is None: _UpperCAmelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _UpperCAmelCase = model_inputs.pop(self.model.main_input_name ) _UpperCAmelCase = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = [] for output_ids in model_outputs: _UpperCAmelCase = { 'generated_text': self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
329
1
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ :Tuple = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[int] = PegasusTokenizer _a : Union[str, Any] = PegasusTokenizerFast _a : List[str] = True _a : Tuple = True def UpperCAmelCase__ ( self ) -> int: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _UpperCAmelCase = PegasusTokenizer(_SCREAMING_SNAKE_CASE ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return ("This is a test", "This is a test") def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = '</s>' _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1103 ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) _UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids[0] _UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word _UpperCAmelCase = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' _UpperCAmelCase = [2, 413, 615, 114, 3, 1971, 113, 1679, 10710, 107, 1] _UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE ).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 96103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 _UpperCAmelCase = 'To ensure a smooth flow of bank resolutions.' _UpperCAmelCase = [413, 615, 114, 2291, 1971, 113, 1679, 10710, 107, 1] _UpperCAmelCase = tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE ).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = ['This is going to be way too long.' * 150, 'short example'] _UpperCAmelCase = ['not super long but more than 5 tokens', 'tiny'] _UpperCAmelCase = self._large_tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) _UpperCAmelCase = self._large_tokenizer( text_target=_SCREAMING_SNAKE_CASE , max_length=5 , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(_SCREAMING_SNAKE_CASE ) == 2 # input_ids, attention_mask. @slow def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = {'input_ids': [[38979, 143, 18485, 606, 130, 26669, 87686, 121, 54189, 1129, 111, 26669, 87686, 121, 9114, 14787, 121, 13249, 158, 592, 956, 121, 14621, 31576, 143, 62613, 108, 9688, 930, 43430, 11562, 62613, 304, 108, 11443, 897, 108, 9314, 17415, 63399, 108, 11443, 7614, 18316, 118, 4284, 7148, 12430, 143, 1400, 25703, 158, 111, 4284, 7148, 11772, 143, 21297, 1064, 158, 122, 204, 3506, 1754, 1133, 14787, 1581, 115, 33224, 4482, 111, 1355, 110, 29173, 317, 50833, 108, 20147, 94665, 111, 77198, 107, 1], [110, 62613, 117, 638, 112, 1133, 121, 20098, 1355, 79050, 13872, 135, 1596, 53541, 1352, 141, 13039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 18289, 17780, 204, 109, 9474, 1296, 107, 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]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_SCREAMING_SNAKE_CASE , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = PegasusTokenizer _a : Tuple = PegasusTokenizerFast _a : Union[str, Any] = True _a : List[Any] = True def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing _UpperCAmelCase = PegasusTokenizer(_SCREAMING_SNAKE_CASE , offset=0 , mask_token_sent=_SCREAMING_SNAKE_CASE , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return ("This is a test", "This is a test") def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = self.tokenizer_class.from_pretrained(self.tmpdirname ) _UpperCAmelCase = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) _UpperCAmelCase = rust_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids[0] _UpperCAmelCase = py_tokenizer([raw_input_str] , return_tensors=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids[0] self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @require_torch def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = ['This is going to be way too long.' * 1000, 'short example'] _UpperCAmelCase = ['not super long but more than 5 tokens', 'tiny'] _UpperCAmelCase = self._large_tokenizer(_SCREAMING_SNAKE_CASE , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) _UpperCAmelCase = self._large_tokenizer( text_target=_SCREAMING_SNAKE_CASE , max_length=5 , padding=_SCREAMING_SNAKE_CASE , truncation=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(_SCREAMING_SNAKE_CASE ) == 2 # input_ids, attention_mask. def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) _UpperCAmelCase = self._large_tokenizer(_SCREAMING_SNAKE_CASE ).input_ids self.assertListEqual( _SCREAMING_SNAKE_CASE , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 25016, 3137, 464, 109, 26955, 3137, 1] , )
329
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = { '''google/realm-cc-news-pretrained-embedder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-encoder''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-scorer''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/config.json''' ), '''google/realm-cc-news-pretrained-openqa''': ( '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/config.json''' ), '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/config.json''', '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/config.json''', '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/config.json''', '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/config.json''', # See all REALM models at https://huggingface.co/models?filter=realm } class __a ( UpperCAmelCase ): _a : List[Any] = 'realm' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu_new" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=1e-3 , _SCREAMING_SNAKE_CASE=5 , _SCREAMING_SNAKE_CASE=320 , _SCREAMING_SNAKE_CASE=13353718 , _SCREAMING_SNAKE_CASE=5000 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , **_SCREAMING_SNAKE_CASE , ) -> Dict: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) # Common config _UpperCAmelCase = vocab_size _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = hidden_size _UpperCAmelCase = retriever_proj_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = num_candidates _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = initializer_range _UpperCAmelCase = type_vocab_size _UpperCAmelCase = layer_norm_eps # Reader config _UpperCAmelCase = span_hidden_size _UpperCAmelCase = max_span_width _UpperCAmelCase = reader_layer_norm_eps _UpperCAmelCase = reader_beam_size _UpperCAmelCase = reader_seq_len # Retrieval config _UpperCAmelCase = num_block_records _UpperCAmelCase = searcher_beam_size
329
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
1
import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCAmelCase__ :List[str] = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(3_2, (3, 3), input_shape=(6_4, 6_4, 3), activation='''relu''') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(3_2, (3, 3), activation='''relu''')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=1_2_8, activation='''relu''')) classifier.add(layers.Dense(units=1, activation='''sigmoid''')) # Compiling the CNN classifier.compile( optimizer='''adam''', loss='''binary_crossentropy''', metrics=['''accuracy'''] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCAmelCase__ :Optional[Any] = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 2_5_5, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCAmelCase__ :int = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 2_5_5) lowerCAmelCase__ :Union[str, Any] = train_datagen.flow_from_directory( '''dataset/training_set''', target_size=(6_4, 6_4), batch_size=3_2, class_mode='''binary''' ) lowerCAmelCase__ :Optional[int] = test_datagen.flow_from_directory( '''dataset/test_set''', target_size=(6_4, 6_4), batch_size=3_2, class_mode='''binary''' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=3_0, validation_data=test_set ) classifier.save('''cnn.h5''') # Part 3 - Making new predictions lowerCAmelCase__ :Optional[int] = tf.keras.preprocessing.image.load_img( '''dataset/single_prediction/image.png''', target_size=(6_4, 6_4) ) lowerCAmelCase__ :Tuple = tf.keras.preprocessing.image.img_to_array(test_image) lowerCAmelCase__ :Optional[int] = np.expand_dims(test_image, axis=0) lowerCAmelCase__ :Tuple = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCAmelCase__ :Optional[Any] = '''Normal''' if result[0][0] == 1: lowerCAmelCase__ :Union[str, Any] = '''Abnormality detected'''
329
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
1
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class __a : def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return None class __a : def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return None class __a ( unittest.TestCase ): _a : int = [ # (model_name, model_kwargs) ('bert-base-cased', {}), ('gpt2', {'use_cache': False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(_SCREAMING_SNAKE_CASE , 'tf' , 12 , **_SCREAMING_SNAKE_CASE ) @require_torch @slow def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(_SCREAMING_SNAKE_CASE , 'pt' , 12 , **_SCREAMING_SNAKE_CASE ) @require_torch @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" from transformers import BertModel _UpperCAmelCase = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(_SCREAMING_SNAKE_CASE ) ) vocab_file.flush() _UpperCAmelCase = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: _UpperCAmelCase = BertModel(BertConfig(vocab_size=len(_SCREAMING_SNAKE_CASE ) ) ) model.save_pretrained(_SCREAMING_SNAKE_CASE ) self._test_export(_SCREAMING_SNAKE_CASE , 'pt' , 12 , _SCREAMING_SNAKE_CASE ) @require_tf @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _UpperCAmelCase = self._test_export(_SCREAMING_SNAKE_CASE , 'tf' , 12 , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = quantize(Path(_SCREAMING_SNAKE_CASE ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(_SCREAMING_SNAKE_CASE ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: _UpperCAmelCase = self._test_export(_SCREAMING_SNAKE_CASE , 'pt' , 12 , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = quantize(_SCREAMING_SNAKE_CASE ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(_SCREAMING_SNAKE_CASE ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" try: # Compute path with TemporaryDirectory() as tempdir: _UpperCAmelCase = Path(_SCREAMING_SNAKE_CASE ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return path except Exception as e: self.fail(_SCREAMING_SNAKE_CASE ) @require_torch @require_tokenizers @slow def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" from transformers import BertModel _UpperCAmelCase = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) _UpperCAmelCase = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'pt' ) @require_tf @require_tokenizers @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" from transformers import TFBertModel _UpperCAmelCase = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) _UpperCAmelCase = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , 'tf' ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _UpperCAmelCase = FeatureExtractionPipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = infer_shapes(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Assert all variables are present self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , _SCREAMING_SNAKE_CASE ) self.assertSequenceEqual(variable_names[3:] , _SCREAMING_SNAKE_CASE ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: 'batch', 1: 'sequence'} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['output_0'] , {0: 'batch', 1: 'sequence'} ) self.assertDictEqual(shapes['output_1'] , {0: 'batch'} ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = ['input_ids', 'attention_mask', 'token_type_ids'] _UpperCAmelCase = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} _UpperCAmelCase , _UpperCAmelCase = ensure_valid_input(FuncContiguousArgs() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 3 ) # Should have exactly the same input names self.assertEqual(set(_SCREAMING_SNAKE_CASE ) , set(_SCREAMING_SNAKE_CASE ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(_SCREAMING_SNAKE_CASE , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) _UpperCAmelCase , _UpperCAmelCase = ensure_valid_input(FuncNonContiguousArgs() , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['input_ids'] ) self.assertEqual(ordered_input_names[0] , 'input_ids' ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
329
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = AutoConfig.from_pretrained(a__ ) _UpperCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=a__ ) _UpperCAmelCase = checkpoints.load_tax_checkpoint(a__ ) _UpperCAmelCase = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": _UpperCAmelCase = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": _UpperCAmelCase = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['encoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_global_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = tax_mlp_layer_norm _UpperCAmelCase = flax_model_encoder_layer_block # Only for layer 0: _UpperCAmelCase = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_global_rel_embedding # Assigning _UpperCAmelCase = tax_model['target']['encoder']['encoder_norm']['scale'] _UpperCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] _UpperCAmelCase = tax_enc_dec_attention_module['key']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['out']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['query']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['decoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_pre_attention_layer_norm _UpperCAmelCase = tax_enc_dec_attention_key _UpperCAmelCase = tax_enc_dec_attention_out _UpperCAmelCase = tax_enc_dec_attention_query _UpperCAmelCase = tax_enc_dec_attention_value _UpperCAmelCase = tax_cross_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = txa_mlp_layer_norm _UpperCAmelCase = flax_model_decoder_layer_block # Decoder Normalization _UpperCAmelCase = tax_model['target']['decoder']['decoder_norm']['scale'] _UpperCAmelCase = txa_decoder_norm # Only for layer 0: _UpperCAmelCase = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_decoder_rel_embedding # Token Embeddings _UpperCAmelCase = tax_model['target']['token_embedder']['embedding'] _UpperCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: _UpperCAmelCase = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(a__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path the T5X checkpoint.''' ) parser.add_argument('''--config_name''', default=None, type=str, required=True, help='''Config name of LongT5/T5 model.''') parser.add_argument( '''--flax_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output FLAX model.''' ) lowerCAmelCase__ :List[str] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
329
1
from __future__ import annotations from functools import lru_cache from math import ceil lowerCAmelCase__ :Tuple = 1_0_0 lowerCAmelCase__ :Tuple = set(range(3, NUM_PRIMES, 2)) primes.add(2) lowerCAmelCase__ :int for prime in range(3, ceil(NUM_PRIMES**0.5), 2): if prime not in primes: continue primes.difference_update(set(range(prime * prime, NUM_PRIMES, prime))) @lru_cache(maxsize=1_0_0 ) def lowerCAmelCase__ ( a__: int ) -> set[int]: '''simple docstring''' if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} _UpperCAmelCase = set() _UpperCAmelCase = 42 _UpperCAmelCase = 42 for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime ): ret.add(sub * prime ) return ret def lowerCAmelCase__ ( a__: int = 5_0_0_0 ) -> int | None: '''simple docstring''' for number_to_partition in range(1 , a__ ): if len(partition(a__ ) ) > number_unique_partitions: return number_to_partition return None if __name__ == "__main__": print(f'''{solution() = }''')
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : str = 'ctrl' _a : Tuple = ['past_key_values'] _a : List[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=246534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
def lowerCAmelCase__ ( a__: list ) -> list: '''simple docstring''' if any(not isinstance(a__ , a__ ) or x < 0 for x in sequence ): raise TypeError('Sequence must be list of non-negative integers' ) for _ in range(len(a__ ) ): for i, (rod_upper, rod_lower) in enumerate(zip(a__ , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
329
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> Dict: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : str = DeformableDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DeformableDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = 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 , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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, ) , ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = DeformableDetrImageProcessor() _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = DeformableDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
329
1
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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Any = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: str ) -> YolosConfig: '''simple docstring''' _UpperCAmelCase = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _UpperCAmelCase = 1_9_2 _UpperCAmelCase = 7_6_8 _UpperCAmelCase = 1_2 _UpperCAmelCase = 3 _UpperCAmelCase = [8_0_0, 1_3_3_3] _UpperCAmelCase = False elif yolos_name == "yolos_s_dWr": _UpperCAmelCase = 3_3_0 _UpperCAmelCase = 1_4 _UpperCAmelCase = 6 _UpperCAmelCase = 1_3_2_0 elif "yolos_s" in yolos_name: _UpperCAmelCase = 3_8_4 _UpperCAmelCase = 1_5_3_6 _UpperCAmelCase = 1_2 _UpperCAmelCase = 6 elif "yolos_b" in yolos_name: _UpperCAmelCase = [8_0_0, 1_3_4_4] _UpperCAmelCase = 9_1 _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = 'coco-detection-id2label.json' _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} return config def lowerCAmelCase__ ( a__: dict , a__: YolosConfig , a__: bool = False ) -> Union[str, 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) _UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' ) _UpperCAmelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _UpperCAmelCase = in_proj_weight[: config.hidden_size, :] _UpperCAmelCase = in_proj_bias[: config.hidden_size] _UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCAmelCase = in_proj_weight[-config.hidden_size :, :] _UpperCAmelCase = in_proj_bias[-config.hidden_size :] def lowerCAmelCase__ ( a__: str ) -> str: '''simple docstring''' if "backbone" in name: _UpperCAmelCase = name.replace('backbone' , 'vit' ) if "cls_token" in name: _UpperCAmelCase = name.replace('cls_token' , 'embeddings.cls_token' ) if "det_token" in name: _UpperCAmelCase = name.replace('det_token' , 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: _UpperCAmelCase = name.replace('mid_pos_embed' , 'encoder.mid_position_embeddings' ) if "pos_embed" in name: _UpperCAmelCase = name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: _UpperCAmelCase = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "blocks" in name: _UpperCAmelCase = name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: _UpperCAmelCase = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: _UpperCAmelCase = name.replace('attn' , 'attention.self' ) if "norm1" in name: _UpperCAmelCase = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _UpperCAmelCase = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _UpperCAmelCase = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _UpperCAmelCase = name.replace('mlp.fc2' , 'output.dense' ) if "class_embed" in name: _UpperCAmelCase = name.replace('class_embed' , 'class_labels_classifier' ) if "bbox_embed" in name: _UpperCAmelCase = name.replace('bbox_embed' , 'bbox_predictor' ) if "vit.norm" in name: _UpperCAmelCase = name.replace('vit.norm' , 'vit.layernorm' ) return name def lowerCAmelCase__ ( a__: dict , a__: YolosForObjectDetection ) -> dict: '''simple docstring''' for key in orig_state_dict.copy().keys(): _UpperCAmelCase = orig_state_dict.pop(a__ ) if "qkv" in key: _UpperCAmelCase = key.split('.' ) _UpperCAmelCase = int(key_split[2] ) _UpperCAmelCase = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _UpperCAmelCase = val[:dim, :] _UpperCAmelCase = val[ dim : dim * 2, : ] _UpperCAmelCase = val[-dim:, :] else: _UpperCAmelCase = val[:dim] _UpperCAmelCase = val[dim : dim * 2] _UpperCAmelCase = val[-dim:] else: _UpperCAmelCase = val return orig_state_dict def lowerCAmelCase__ ( ) -> torch.Tensor: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return im @torch.no_grad() def lowerCAmelCase__ ( a__: str , a__: str , a__: str , a__: bool = False ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = get_yolos_config(a__ ) # load original state_dict _UpperCAmelCase = torch.load(a__ , map_location='cpu' )['model'] # load 🤗 model _UpperCAmelCase = YolosForObjectDetection(a__ ) model.eval() _UpperCAmelCase = convert_state_dict(a__ , a__ ) model.load_state_dict(a__ ) # Check outputs on an image, prepared by YolosImageProcessor _UpperCAmelCase = 8_0_0 if yolos_name != 'yolos_ti' else 5_1_2 _UpperCAmelCase = YolosImageProcessor(format='coco_detection' , size=a__ ) _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ) _UpperCAmelCase = model(**a__ ) _UpperCAmelCase , _UpperCAmelCase = outputs.logits, outputs.pred_boxes _UpperCAmelCase , _UpperCAmelCase = None, None if yolos_name == "yolos_ti": _UpperCAmelCase = torch.tensor( [[-39.5_022, -11.9_820, -17.6_888], [-29.9_574, -9.9_769, -17.7_691], [-42.3_281, -20.7_200, -30.6_294]] ) _UpperCAmelCase = torch.tensor( [[0.4_021, 0.0_836, 0.7_979], [0.0_184, 0.2_609, 0.0_364], [0.1_781, 0.2_004, 0.2_095]] ) elif yolos_name == "yolos_s_200_pre": _UpperCAmelCase = torch.tensor( [[-24.0_248, -10.3_024, -14.8_290], [-42.0_392, -16.8_200, -27.4_334], [-27.2_743, -11.8_154, -18.7_148]] ) _UpperCAmelCase = torch.tensor( [[0.2_559, 0.5_455, 0.4_706], [0.2_989, 0.7_279, 0.1_875], [0.7_732, 0.4_017, 0.4_462]] ) elif yolos_name == "yolos_s_300_pre": _UpperCAmelCase = torch.tensor( [[-36.2_220, -14.4_385, -23.5_457], [-35.6_970, -14.7_583, -21.3_935], [-31.5_939, -13.6_042, -16.8_049]] ) _UpperCAmelCase = torch.tensor( [[0.7_614, 0.2_316, 0.4_728], [0.7_168, 0.4_495, 0.3_855], [0.4_996, 0.1_466, 0.9_996]] ) elif yolos_name == "yolos_s_dWr": _UpperCAmelCase = torch.tensor( [[-42.8_668, -24.1_049, -41.1_690], [-34.7_456, -14.1_274, -24.9_194], [-33.7_898, -12.1_946, -25.6_495]] ) _UpperCAmelCase = torch.tensor( [[0.5_587, 0.2_773, 0.0_605], [0.5_004, 0.3_014, 0.9_994], [0.4_999, 0.1_548, 0.9_994]] ) elif yolos_name == "yolos_base": _UpperCAmelCase = torch.tensor( [[-40.6_064, -24.3_084, -32.6_447], [-55.1_990, -30.7_719, -35.5_877], [-51.4_311, -33.3_507, -35.6_462]] ) _UpperCAmelCase = torch.tensor( [[0.5_555, 0.2_794, 0.0_655], [0.9_049, 0.2_664, 0.1_894], [0.9_183, 0.1_984, 0.1_635]] ) else: raise ValueError(F'''Unknown yolos_name: {yolos_name}''' ) assert torch.allclose(logits[0, :3, :3] , a__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , a__ , atol=1e-4 ) Path(a__ ).mkdir(exist_ok=a__ ) print(F'''Saving model {yolos_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if push_to_hub: _UpperCAmelCase = { 'yolos_ti': 'yolos-tiny', 'yolos_s_200_pre': 'yolos-small', 'yolos_s_300_pre': 'yolos-small-300', 'yolos_s_dWr': 'yolos-small-dwr', 'yolos_base': 'yolos-base', } print('Pushing to the hub...' ) _UpperCAmelCase = model_mapping[yolos_name] image_processor.push_to_hub(a__ , organization='hustvl' ) model.push_to_hub(a__ , organization='hustvl' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--yolos_name''', default='''yolos_s_200_pre''', type=str, help=( '''Name of the YOLOS model you\'d like to convert. Should be one of \'yolos_ti\', \'yolos_s_200_pre\',''' ''' \'yolos_s_300_pre\', \'yolos_s_dWr\', \'yolos_base\'.''' ), ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original state dict (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) lowerCAmelCase__ :Optional[int] = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
329
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a ( unittest.TestCase ): _a : List[str] = JukeboxTokenizer _a : List[Any] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
329
1
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES 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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=[10, 20, 30, 40] , _SCREAMING_SNAKE_CASE=[2, 2, 3, 2] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=["stage2", "stage3", "stage4"] , _SCREAMING_SNAKE_CASE=[2, 3, 4] , _SCREAMING_SNAKE_CASE=None , ) -> Any: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = num_channels _UpperCAmelCase = num_stages _UpperCAmelCase = hidden_sizes _UpperCAmelCase = depths _UpperCAmelCase = is_training _UpperCAmelCase = use_labels _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = num_labels _UpperCAmelCase = initializer_range _UpperCAmelCase = out_features _UpperCAmelCase = out_indices _UpperCAmelCase = scope def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ConvNextVaModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = ConvNextVaForImageClassification(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _UpperCAmelCase = None _UpperCAmelCase = ConvNextVaBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) _a : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) _a : Any = False _a : int = False _a : str = False _a : List[str] = False _a : Union[str, Any] = False def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = ConvNextVaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , has_text_modality=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_with_labels() _UpperCAmelCase = True if model_class.__name__ in [ *get_values(_SCREAMING_SNAKE_CASE ), *get_values(_SCREAMING_SNAKE_CASE ), ]: continue _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.train() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE ).loss loss.backward() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" if not self.model_tester.is_training: return for model_class in self.all_model_classes: _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_with_labels() _UpperCAmelCase = False _UpperCAmelCase = True if ( model_class.__name__ in [*get_values(_SCREAMING_SNAKE_CASE ), *get_values(_SCREAMING_SNAKE_CASE )] or not model_class.supports_gradient_checkpointing ): continue _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.train() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE ).loss loss.backward() def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" def check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _UpperCAmelCase = self.model_tester.num_stages self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = 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"] _UpperCAmelCase = True check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = ConvNextVaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __a ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = preprocessor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' ).to(_SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE ) # verify the logits _UpperCAmelCase = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.9996, 0.1966, -0.4386] ).to(_SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
329
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ :Optional[int] = logging.getLogger(__name__) def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = argparse.ArgumentParser( description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.' ) parser.add_argument( '--dataset_name' , type=a__ , default='wikitext' , help='Name of the training. Explore datasets at: hf.co/datasets.' , ) parser.add_argument( '--dataset_config' , type=a__ , default='wikitext-103-raw-v1' , help='Configuration name of the dataset.' ) parser.add_argument( '--tokenizer_name_or_path' , type=a__ , default='sayakpaul/unigram-tokenizer-wikitext' , help='Tokenizer identifier. Can be a local filepath or a Hub identifier.' , ) parser.add_argument( '--shard_size' , type=a__ , default=1_0_0_0 , help='Number of entries to go in a single shard.' , ) parser.add_argument('--split' , type=a__ , default='train' , choices=['train', 'test', 'validation'] ) parser.add_argument( '--limit' , default=a__ , type=a__ , help='Limit the number of shards (used for debugging).' , ) parser.add_argument( '--max_length' , type=a__ , default=5_1_2 , help='Maximum sequence length. For training on TPUs, it helps to have a maximum' ' sequence length that is a multiple of 8.' , ) parser.add_argument( '--output_dir' , default='tf-tpu' , type=a__ , help='Output directory where the TFRecord shards will be saved. If the' ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord' ' shards will be directly saved to a Google Cloud Storage bucket.' , ) _UpperCAmelCase = parser.parse_args() return args def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[Any]: '''simple docstring''' def fn(a__: str ): return tokenizer(examples['text'] ) return fn def lowerCAmelCase__ ( a__: List[str] ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for i in range(len(tokenized_data['input_ids'] ) ): _UpperCAmelCase = { 'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i] ) ), 'attention_mask': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i] ) ), } _UpperCAmelCase = tf.train.Features(feature=a__ ) _UpperCAmelCase = tf.train.Example(features=a__ ) _UpperCAmelCase = example.SerializeToString() records.append(a__ ) return records def lowerCAmelCase__ ( a__: Union[str, Any] ) -> int: '''simple docstring''' _UpperCAmelCase = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: _UpperCAmelCase = min(len(a__ ) , args.limit ) _UpperCAmelCase = dataset.select(range(a__ ) ) print(F'''Limiting the dataset to {args.limit} entries.''' ) _UpperCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _UpperCAmelCase = os.path.join(args.output_dir , args.split ) if not os.path.exists(a__ ): os.makedirs(a__ ) else: _UpperCAmelCase = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. _UpperCAmelCase = tokenize_function(a__ ) _UpperCAmelCase = dataset.map(a__ , batched=a__ , num_proc=4 , remove_columns=['text'] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(a__: Optional[int] ): # Concatenate all texts. _UpperCAmelCase = {k: sum(examples[k] , [] ) for k in examples.keys()} _UpperCAmelCase = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _UpperCAmelCase = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _UpperCAmelCase = { k: [t[i : i + args.max_length] for i in range(0 , a__ , args.max_length )] for k, t in concatenated_examples.items() } return result _UpperCAmelCase = dataset_tokenized.map(a__ , batched=a__ , batch_size=1_0_0_0 , num_proc=4 ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 for shard in range(0 , len(a__ ) , args.shard_size ): _UpperCAmelCase = grouped_dataset[shard : shard + args.shard_size] _UpperCAmelCase = len(dataset_snapshot['input_ids'] ) _UpperCAmelCase = os.path.join(a__ , F'''dataset-{shard_count}-{records_containing}.tfrecord''' ) _UpperCAmelCase = get_serialized_examples(a__ ) with tf.io.TFRecordWriter(a__ ) as out_file: for i in range(len(a__ ) ): _UpperCAmelCase = serialized_examples[i] out_file.write(a__ ) print('Wrote file {} containing {} records'.format(a__ , a__ ) ) shard_count += 1 total_records += records_containing with open(F'''split-{args.split}-records-count.txt''' , 'w' ) as f: print(F'''Total {args.split} records: {total_records}''' , file=a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = parse_args() main(args)
329
1
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor lowerCAmelCase__ :Optional[int] = logging.get_logger(__name__) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , _SCREAMING_SNAKE_CASE , ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
329
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any]=1_0 ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for _ in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCAmelCase__ ( a__: List[str] , a__: Any=1_0 ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [] for step in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(a__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , a__ ) _UpperCAmelCase = torch.load(a__ ) scheduler.load_state_dict(a__ ) return lrs @require_torch class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-3_0, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_SCREAMING_SNAKE_CASE , weight_decay=0.0 , relative_step=_SCREAMING_SNAKE_CASE , scale_parameter=_SCREAMING_SNAKE_CASE , warmup_init=_SCREAMING_SNAKE_CASE , ) for _ in range(1000 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __a ( unittest.TestCase ): _a : Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _a : Dict = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _a : List[Any] = 10 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE , msg=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListAlmostEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tol=1e-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_SCREAMING_SNAKE_CASE ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , msg=f'''failed for {scheduler_func} in save and reload''' ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = fn def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
329
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __a ( UpperCAmelCase ): _a : List[str] = ['image_processor', 'tokenizer'] _a : List[Any] = 'BlipImageProcessor' _a : Tuple = ('BertTokenizer', 'BertTokenizerFast') def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = False super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processor def __call__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: _UpperCAmelCase = self.tokenizer _UpperCAmelCase = self.tokenizer( text=_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_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_token_type_ids=_SCREAMING_SNAKE_CASE , return_length=_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) return text_encoding # add pixel_values _UpperCAmelCase = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) if text is not None: _UpperCAmelCase = self.tokenizer( text=_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_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_token_type_ids=_SCREAMING_SNAKE_CASE , return_length=_SCREAMING_SNAKE_CASE , verbose=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) else: _UpperCAmelCase = None if text_encoding is not None: encoding_image_processor.update(_SCREAMING_SNAKE_CASE ) return encoding_image_processor def UpperCAmelCase__ ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.tokenizer.model_input_names _UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
329
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Any = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any] , a__: Dict , a__: Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = original_name.split('.' )[0] _UpperCAmelCase = key.split('.' ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 2] ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 1] ) _UpperCAmelCase = orig_block_num - offset _UpperCAmelCase = key.replace(F'''{orig_block_num}.{layer_num}.{original_name}''' , F'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def lowerCAmelCase__ ( a__: Tuple ) -> int: '''simple docstring''' _UpperCAmelCase = OrderedDict() _UpperCAmelCase , _UpperCAmelCase = 0, 0 for key, value in state_dict.items(): if key.startswith('network' ): _UpperCAmelCase = key.replace('network' , 'poolformer.encoder' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('bias' ) and "patch_embed" not in key: patch_emb_offset += 1 _UpperCAmelCase = key[: key.find('proj' )] _UpperCAmelCase = key.replace(a__ , F'''patch_embeddings.{total_embed_found}.''' ) _UpperCAmelCase = key.replace('proj' , 'projection' ) if key.endswith('bias' ): total_embed_found += 1 if "patch_embeddings" in key: _UpperCAmelCase = 'poolformer.encoder.' + key if "mlp.fc1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc1' , 'output.conv1' ) if "mlp.fc2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc2' , 'output.conv2' ) if "norm1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm1' , 'before_norm' ) if "norm2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm2' , 'after_norm' ) if "layer_scale_1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_1' , 'layer_scale_1' ) if "layer_scale_2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_2' , 'layer_scale_2' ) if "head" in key: _UpperCAmelCase = key.replace('head' , 'classifier' ) _UpperCAmelCase = value return new_state_dict def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return image @torch.no_grad() def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: Any ) -> Dict: '''simple docstring''' _UpperCAmelCase = PoolFormerConfig() # set attributes based on model_name _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = model_name[-3:] _UpperCAmelCase = 1_0_0_0 _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = (1, 1_0_0_0) # set config attributes _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} if size == "s12": _UpperCAmelCase = [2, 2, 6, 2] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s24": _UpperCAmelCase = [4, 4, 1_2, 4] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.9 elif size == "m36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 elif size == "m48": _UpperCAmelCase = [8, 8, 2_4, 8] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 else: raise ValueError(F'''Size {size} not supported''' ) # load image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) # Prepare image _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) # rename keys _UpperCAmelCase = rename_keys(a__ ) # create HuggingFace model and load state dict _UpperCAmelCase = PoolFormerForImageClassification(a__ ) model.load_state_dict(a__ ) model.eval() # Define image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values # forward pass _UpperCAmelCase = model(a__ ) _UpperCAmelCase = outputs.logits # define expected logit slices for different models if size == "s12": _UpperCAmelCase = torch.tensor([-0.3_045, -0.6_758, -0.4_869] ) elif size == "s24": _UpperCAmelCase = torch.tensor([0.4_402, -0.1_374, -0.8_045] ) elif size == "s36": _UpperCAmelCase = torch.tensor([-0.6_080, -0.5_133, -0.5_898] ) elif size == "m36": _UpperCAmelCase = torch.tensor([0.3_952, 0.2_263, -1.2_668] ) elif size == "m48": _UpperCAmelCase = torch.tensor([0.1_167, -0.0_656, -0.3_423] ) else: raise ValueError(F'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , a__ , atol=1e-2 ) # finally, save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(a__ ).mkdir(exist_ok=a__ ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
329
1
from heapq import heappop, heappush import numpy as np def lowerCAmelCase__ ( a__: np.ndarray , a__: tuple[int, int] , a__: tuple[int, int] , a__: bool , ) -> tuple[float | int, list[tuple[int, int]]]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = grid.shape _UpperCAmelCase = [-1, 1, 0, 0] _UpperCAmelCase = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] _UpperCAmelCase , _UpperCAmelCase = [(0, source)], set() _UpperCAmelCase = np.full((rows, cols) , np.inf ) _UpperCAmelCase = 0 _UpperCAmelCase = np.empty((rows, cols) , dtype=a__ ) _UpperCAmelCase = None while queue: ((_UpperCAmelCase) , (_UpperCAmelCase)) = heappop(a__ ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: _UpperCAmelCase = [] while (x, y) != source: path.append((x, y) ) _UpperCAmelCase , _UpperCAmelCase = predecessors[x, y] path.append(a__ ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(a__ ) ): _UpperCAmelCase , _UpperCAmelCase = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: _UpperCAmelCase = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(a__ , (dist + 1, (nx, ny)) ) _UpperCAmelCase = dist + 1 _UpperCAmelCase = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
329
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = process _UpperCAmelCase = params def __len__( self ) -> Union[str, Any]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = self.dataset[i] _UpperCAmelCase = self.process(_SCREAMING_SNAKE_CASE , **self.params ) return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = loader _UpperCAmelCase = infer _UpperCAmelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether _UpperCAmelCase = None _UpperCAmelCase = loader_batch_size # Internal bookkeeping _UpperCAmelCase = None _UpperCAmelCase = None def __len__( self ) -> Any: """simple docstring""" return len(self.loader ) def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice _UpperCAmelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) _UpperCAmelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Convert ModelOutput to tuple first _UpperCAmelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around _UpperCAmelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. _UpperCAmelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 _UpperCAmelCase = self._loader_batch_data.__class__(_SCREAMING_SNAKE_CASE ) self._loader_batch_index += 1 return result def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch _UpperCAmelCase = next(self.iterator ) _UpperCAmelCase = self.infer(_SCREAMING_SNAKE_CASE , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size # Setting internal index to unwrap the batch _UpperCAmelCase = processed _UpperCAmelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __iter__( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) _UpperCAmelCase = None return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if self.subiterator is None: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item _UpperCAmelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) _UpperCAmelCase = next(self.subiterator ) return processed class __a ( UpperCAmelCase ): def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = False _UpperCAmelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator while not is_last: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size _UpperCAmelCase = processed _UpperCAmelCase = 0 while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator else: _UpperCAmelCase = processed _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) return accumulator class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = key def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return self.dataset[i][self.key] class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = keya _UpperCAmelCase = keya def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
329
1
from __future__ import annotations def lowerCAmelCase__ ( a__: list[int] , a__: int ) -> list[int]: '''simple docstring''' _UpperCAmelCase = 0 _UpperCAmelCase = len(a__ ) - 1 while i < j: if nums[i] + nums[j] == target: return [i, j] elif nums[i] + nums[j] < target: _UpperCAmelCase = i + 1 else: _UpperCAmelCase = j - 1 return [] if __name__ == "__main__": import doctest doctest.testmod() print(f'''{two_pointer([2, 7, 1_1, 1_5], 9) = }''')
329
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __a ( UpperCAmelCase ): _a : str = 'data2vec-text' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = position_embedding_type _UpperCAmelCase = use_cache _UpperCAmelCase = classifier_dropout class __a ( UpperCAmelCase ): @property def UpperCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
329
1
def lowerCAmelCase__ ( a__: bytes ) -> str: '''simple docstring''' return "".join([hex(a__ )[2:].zfill(2 ).upper() for byte in list(a__ )] ) def lowerCAmelCase__ ( a__: str ) -> bytes: '''simple docstring''' if (len(a__ ) % 2) != 0: raise ValueError( 'Base16 encoded data is invalid:\nData does not have an even number of hex digits.' ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(a__ ) <= set('0123456789ABCDEF' ): raise ValueError( 'Base16 encoded data is invalid:\nData is not uppercase hex or it contains invalid characters.' ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1] , 1_6 ) for i in range(0 , len(a__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
329
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> List[str]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = depths _UpperCAmelCase = num_heads _UpperCAmelCase = window_size _UpperCAmelCase = mlp_ratio _UpperCAmelCase = qkv_bias _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = hidden_act _UpperCAmelCase = use_absolute_embeddings _UpperCAmelCase = patch_norm _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = is_training _UpperCAmelCase = scope _UpperCAmelCase = use_labels _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = encoder_stride _UpperCAmelCase = out_features _UpperCAmelCase = out_indices def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _UpperCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = ['stem'] _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _a : str = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} _a : Optional[int] = False _a : List[str] = False _a : List[str] = False _a : Optional[int] = False _a : Tuple = False def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip('Swin does not use inputs_embeds' ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" pass @unittest.skip('Swin does not support feedforward chunking' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = 3 _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _UpperCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has''' f''' `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}.''' ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) @require_torch class __a ( unittest.TestCase , UpperCAmelCase ): _a : Any = (MaskFormerSwinBackbone,) if is_torch_available() else () _a : Any = MaskFormerSwinConfig def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: _UpperCAmelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
329
1
lowerCAmelCase__ :str = 2_5_6 # Modulus to hash a string lowerCAmelCase__ :str = 1_0_0_0_0_0_3 def lowerCAmelCase__ ( a__: str , a__: str ) -> bool: '''simple docstring''' _UpperCAmelCase = len(a__ ) _UpperCAmelCase = len(a__ ) if p_len > t_len: return False _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 1 # Calculating the hash of pattern and substring of text for i in range(a__ ): _UpperCAmelCase = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus _UpperCAmelCase = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue _UpperCAmelCase = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash _UpperCAmelCase = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def lowerCAmelCase__ ( ) -> None: '''simple docstring''' _UpperCAmelCase = 'abc1abc12' _UpperCAmelCase = 'alskfjaldsabc1abc1abc12k23adsfabcabc' _UpperCAmelCase = 'alskfjaldsk23adsfabcabc' assert rabin_karp(a__ , a__ ) and not rabin_karp(a__ , a__ ) # Test 2) _UpperCAmelCase = 'ABABX' _UpperCAmelCase = 'ABABZABABYABABX' assert rabin_karp(a__ , a__ ) # Test 3) _UpperCAmelCase = 'AAAB' _UpperCAmelCase = 'ABAAAAAB' assert rabin_karp(a__ , a__ ) # Test 4) _UpperCAmelCase = 'abcdabcy' _UpperCAmelCase = 'abcxabcdabxabcdabcdabcy' assert rabin_karp(a__ , a__ ) # Test 5) _UpperCAmelCase = 'Lü' _UpperCAmelCase = 'Lüsai' assert rabin_karp(a__ , a__ ) _UpperCAmelCase = 'Lue' assert not rabin_karp(a__ , a__ ) print('Success.' ) if __name__ == "__main__": test_rabin_karp()
329
from collections.abc import Generator def lowerCAmelCase__ ( ) -> Generator[int, None, None]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = 0, 1 while True: _UpperCAmelCase , _UpperCAmelCase = b, a + b yield b def lowerCAmelCase__ ( a__: int = 1_0_0_0 ) -> int: '''simple docstring''' _UpperCAmelCase = 1 _UpperCAmelCase = fibonacci_generator() while len(str(next(a__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
329
1
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(UpperCAmelCase ) , 'Tatoeba directory does not exist.' ) class __a ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() return TatoebaConverter(save_dir=_SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" self.resolver.convert_models(['heb-eng'] ) @slow def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.resolver.write_model_card('opus-mt-he-en' , dry_run=_SCREAMING_SNAKE_CASE ) assert mmeta["long_pair"] == "heb-eng"
329
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
1
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=99 , _SCREAMING_SNAKE_CASE=36 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=37 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=6 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=4 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=1000 , ) -> Dict: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = is_training _UpperCAmelCase = use_input_mask _UpperCAmelCase = use_token_type_ids _UpperCAmelCase = use_labels _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = initializer_range _UpperCAmelCase = coordinate_size _UpperCAmelCase = shape_size _UpperCAmelCase = num_labels _UpperCAmelCase = num_choices _UpperCAmelCase = scope _UpperCAmelCase = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) _UpperCAmelCase = text_seq_length _UpperCAmelCase = (image_size // patch_size) ** 2 + 1 _UpperCAmelCase = self.text_seq_length + self.image_seq_length def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) _UpperCAmelCase = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: _UpperCAmelCase = bbox[i, j, 3] _UpperCAmelCase = bbox[i, j, 1] _UpperCAmelCase = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: _UpperCAmelCase = bbox[i, j, 2] _UpperCAmelCase = bbox[i, j, 0] _UpperCAmelCase = tmp_coordinate _UpperCAmelCase = tf.constant(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_input_mask: _UpperCAmelCase = random_attention_mask([self.batch_size, self.text_seq_length] ) _UpperCAmelCase = None if self.use_token_type_ids: _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) _UpperCAmelCase = None _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) _UpperCAmelCase = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = TFLayoutLMvaModel(config=_SCREAMING_SNAKE_CASE ) # text + image _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model( _SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only _UpperCAmelCase = model({'pixel_values': pixel_values} , training=_SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.num_labels _UpperCAmelCase = TFLayoutLMvaForSequenceClassification(config=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model( _SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.num_labels _UpperCAmelCase = TFLayoutLMvaForTokenClassification(config=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model( _SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , labels=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _UpperCAmelCase = 2 _UpperCAmelCase = TFLayoutLMvaForQuestionAnswering(config=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model( _SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , token_type_ids=_SCREAMING_SNAKE_CASE , start_positions=_SCREAMING_SNAKE_CASE , end_positions=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() ((_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase) , (_UpperCAmelCase)) = config_and_inputs _UpperCAmelCase = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : Optional[int] = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) _a : Union[str, Any] = ( {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel} if is_tf_available() else {} ) _a : Any = False _a : List[Any] = False _a : Optional[Any] = False def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return True def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> dict: """simple docstring""" _UpperCAmelCase = copy.deepcopy(_SCREAMING_SNAKE_CASE ) if model_class in get_values(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = { k: tf.tile(tf.expand_dims(_SCREAMING_SNAKE_CASE , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(_SCREAMING_SNAKE_CASE , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) _UpperCAmelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = TFLayoutLMvaModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , hidden_size=37 ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) if getattr(_SCREAMING_SNAKE_CASE , 'hf_compute_loss' , _SCREAMING_SNAKE_CASE ): # The number of elements in the loss should be the same as the number of elements in the label _UpperCAmelCase = self._prepare_for_class(inputs_dict.copy() , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=_SCREAMING_SNAKE_CASE )[0] ] _UpperCAmelCase = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs _UpperCAmelCase = self._prepare_for_class(inputs_dict.copy() , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = prepared_for_class.pop('input_ids' ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions _UpperCAmelCase = self._prepare_for_class(inputs_dict.copy() , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: _UpperCAmelCase = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: _UpperCAmelCase = -100 _UpperCAmelCase = tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict _UpperCAmelCase = self._prepare_for_class(inputs_dict.copy() , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple _UpperCAmelCase = self._prepare_for_class(inputs_dict.copy() , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) # Get keys that were added with the _prepare_for_class function _UpperCAmelCase = prepared_for_class.keys() - inputs_dict.keys() _UpperCAmelCase = inspect.signature(model.call ).parameters _UpperCAmelCase = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple _UpperCAmelCase = {0: 'input_ids'} for label_key in label_keys: _UpperCAmelCase = signature_names.index(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = label_key _UpperCAmelCase = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple _UpperCAmelCase = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: _UpperCAmelCase = prepared_for_class[value] _UpperCAmelCase = tuple(_SCREAMING_SNAKE_CASE ) # Send to model _UpperCAmelCase = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _UpperCAmelCase = type self.model_tester.create_and_check_model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" ( ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ( _UpperCAmelCase ) , ) = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = TFLayoutLMvaModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class __a ( unittest.TestCase ): @cached_property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return LayoutLMvaImageProcessor(apply_ocr=_SCREAMING_SNAKE_CASE ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) _UpperCAmelCase = self.default_image_processor _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors='tf' ).pixel_values _UpperCAmelCase = tf.constant([[1, 2]] ) _UpperCAmelCase = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass _UpperCAmelCase = model(input_ids=_SCREAMING_SNAKE_CASE , bbox=_SCREAMING_SNAKE_CASE , pixel_values=_SCREAMING_SNAKE_CASE , training=_SCREAMING_SNAKE_CASE ) # verify the logits _UpperCAmelCase = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tf.constant( [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) )
329
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 20} _UpperCAmelCase = do_thumbnail _UpperCAmelCase = do_align_axis _UpperCAmelCase = do_pad _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = DonutImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DonutImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 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 , 'do_thumbnail' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_align_long_axis' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , )
329
1
import numpy as np def lowerCAmelCase__ ( a__: np.array ) -> np.array: '''simple docstring''' return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor lowerCAmelCase__ :Tuple = logging.get_logger(__name__) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" warnings.warn( 'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use MobileViTImageProcessor instead.' , _SCREAMING_SNAKE_CASE , ) super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
329
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = {'''configuration_wavlm''': ['''WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''WavLMConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Dict = [ '''WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''WavLMForAudioFrameClassification''', '''WavLMForCTC''', '''WavLMForSequenceClassification''', '''WavLMForXVector''', '''WavLMModel''', '''WavLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys lowerCAmelCase__ :Union[str, Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :List[str] = {'''vocab_file''': '''vocab.txt'''} lowerCAmelCase__ :int = { '''vocab_file''': { '''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''', '''YituTech/conv-bert-medium-small''': ( '''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt''' ), '''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''', } } lowerCAmelCase__ :List[str] = { '''YituTech/conv-bert-base''': 5_1_2, '''YituTech/conv-bert-medium-small''': 5_1_2, '''YituTech/conv-bert-small''': 5_1_2, } lowerCAmelCase__ :Union[str, Any] = { '''YituTech/conv-bert-base''': {'''do_lower_case''': True}, '''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True}, '''YituTech/conv-bert-small''': {'''do_lower_case''': True}, } class __a ( UpperCAmelCase ): _a : Any = VOCAB_FILES_NAMES _a : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _a : Tuple = PRETRAINED_INIT_CONFIGURATION _a : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : Any = ConvBertTokenizer def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> Union[str, Any]: """simple docstring""" super().__init__( _SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , do_lower_case=_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 , tokenize_chinese_chars=_SCREAMING_SNAKE_CASE , strip_accents=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , _SCREAMING_SNAKE_CASE ) != do_lower_case or normalizer_state.get('strip_accents' , _SCREAMING_SNAKE_CASE ) != strip_accents or normalizer_state.get('handle_chinese_chars' , _SCREAMING_SNAKE_CASE ) != tokenize_chinese_chars ): _UpperCAmelCase = getattr(_SCREAMING_SNAKE_CASE , normalizer_state.pop('type' ) ) _UpperCAmelCase = do_lower_case _UpperCAmelCase = strip_accents _UpperCAmelCase = tokenize_chinese_chars _UpperCAmelCase = normalizer_class(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = do_lower_case def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" _UpperCAmelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" _UpperCAmelCase = self._tokenizer.model.save(_SCREAMING_SNAKE_CASE , name=_SCREAMING_SNAKE_CASE ) return tuple(_SCREAMING_SNAKE_CASE )
329
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[str] = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''microsoft/unispeech-sat-base-100h-libri-ft''': ( '''https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json''' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class __a ( UpperCAmelCase ): _a : List[str] = 'unispeech-sat' def __init__( self , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE="group" , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512) , _SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2) , _SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2) , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=128 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.05 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=320 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=100 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="mean" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 1500) , _SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1) , _SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1) , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=504 , **_SCREAMING_SNAKE_CASE , ) -> str: """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 ) _UpperCAmelCase = hidden_size _UpperCAmelCase = feat_extract_norm _UpperCAmelCase = feat_extract_activation _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = conv_bias _UpperCAmelCase = num_conv_pos_embeddings _UpperCAmelCase = num_conv_pos_embedding_groups _UpperCAmelCase = len(self.conv_dim ) _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_act _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_dropout _UpperCAmelCase = attention_dropout _UpperCAmelCase = activation_dropout _UpperCAmelCase = feat_proj_dropout _UpperCAmelCase = final_dropout _UpperCAmelCase = layerdrop _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = vocab_size _UpperCAmelCase = num_clusters _UpperCAmelCase = do_stable_layer_norm _UpperCAmelCase = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==' ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =' f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 _UpperCAmelCase = apply_spec_augment _UpperCAmelCase = mask_time_prob _UpperCAmelCase = mask_time_length _UpperCAmelCase = mask_time_min_masks _UpperCAmelCase = mask_feature_prob _UpperCAmelCase = mask_feature_length _UpperCAmelCase = mask_feature_min_masks # parameters for pretraining with codevector quantized representations _UpperCAmelCase = num_codevectors_per_group _UpperCAmelCase = num_codevector_groups _UpperCAmelCase = contrastive_logits_temperature _UpperCAmelCase = feat_quantizer_dropout _UpperCAmelCase = num_negatives _UpperCAmelCase = codevector_dim _UpperCAmelCase = proj_codevector_dim _UpperCAmelCase = diversity_loss_weight # ctc loss _UpperCAmelCase = ctc_loss_reduction _UpperCAmelCase = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. _UpperCAmelCase = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = xvector_output_dim @property def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return functools.reduce(operator.mul , self.conv_stride , 1 )
329
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _UpperCAmelCase = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE , os.listdir(_SCREAMING_SNAKE_CASE )[0] , 'snapshots' ) )] _UpperCAmelCase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 4 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1514745 ) < 1e-3 assert np.abs(np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 49947.875 ) < 5e-1 _UpperCAmelCase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_SCREAMING_SNAKE_CASE ) == num_samples def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05652401) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2383808.2) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = FlaxDDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = scheduler.create_state() _UpperCAmelCase = scheduler_state _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045043945) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2347693.5) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = jax.random.split(jax.random.PRNGKey(0 ) , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # With memory efficient attention _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , use_memory_efficient_attention=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
329
1
from __future__ import annotations def lowerCAmelCase__ ( a__: list[int] , a__: int ) -> bool: '''simple docstring''' if len(a__ ) == 0: return False _UpperCAmelCase = len(a__ ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , a__ ) else: return binary_search(a_list[midpoint + 1 :] , a__ ) if __name__ == "__main__": lowerCAmelCase__ :Union[str, Any] = input('''Enter numbers separated by comma:\n''').strip() lowerCAmelCase__ :Union[str, Any] = [int(item.strip()) for item in user_input.split(''',''')] lowerCAmelCase__ :List[Any] = int(input('''Enter the number to be found in the list:\n''').strip()) lowerCAmelCase__ :Dict = '''''' if binary_search(sequence, target) else '''not ''' print(f'''{target} was {not_str}found in {sequence}''')
329
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(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ :int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} if prompt is not None: _UpperCAmelCase = prompt if generate_kwargs is not None: _UpperCAmelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _UpperCAmelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,' ' please use only one' ) _UpperCAmelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. ''' 'Note also that one single text can be provided for conditional image to text generation.' ) _UpperCAmelCase = self.model.config.model_type if model_type == "git": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids _UpperCAmelCase = [self.tokenizer.cls_token_id] + input_ids _UpperCAmelCase = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _UpperCAmelCase = None return model_inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs['input_ids'] ) ): _UpperCAmelCase = None if generate_kwargs is None: _UpperCAmelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _UpperCAmelCase = model_inputs.pop(self.model.main_input_name ) _UpperCAmelCase = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = [] for output_ids in model_outputs: _UpperCAmelCase = { 'generated_text': self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
329
1
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
1
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def lowerCAmelCase__ ( a__: int , a__: Union[str, Any]=False ) -> Dict: '''simple docstring''' _UpperCAmelCase = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'''module.blocks.{i}.norm1.weight''', F'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((F'''module.blocks.{i}.norm1.bias''', F'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (F'''module.blocks.{i}.attn.proj.weight''', F'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.attn.proj.bias''', F'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((F'''module.blocks.{i}.norm2.weight''', F'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((F'''module.blocks.{i}.norm2.bias''', F'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc1.weight''', F'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc1.bias''', F'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc2.weight''', F'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((F'''module.blocks.{i}.mlp.fc2.bias''', F'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ('module.cls_token', 'vit.embeddings.cls_token'), ('module.patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('module.patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('module.pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('module.norm.weight', 'layernorm.weight'), ('module.norm.bias', 'layernorm.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" _UpperCAmelCase = [(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) return rename_keys def lowerCAmelCase__ ( a__: Any , a__: Any , a__: Dict=False ) -> int: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: _UpperCAmelCase = '' else: _UpperCAmelCase = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _UpperCAmelCase = state_dict.pop(F'''module.blocks.{i}.attn.qkv.weight''' ) _UpperCAmelCase = state_dict.pop(F'''module.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict _UpperCAmelCase = in_proj_weight[ : config.hidden_size, : ] _UpperCAmelCase = in_proj_bias[: config.hidden_size] _UpperCAmelCase = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _UpperCAmelCase = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _UpperCAmelCase = in_proj_weight[ -config.hidden_size :, : ] _UpperCAmelCase = in_proj_bias[-config.hidden_size :] def lowerCAmelCase__ ( a__: Optional[int] ) -> Any: '''simple docstring''' _UpperCAmelCase = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(a__ , a__ ) def lowerCAmelCase__ ( a__: List[str] ) -> str: '''simple docstring''' _UpperCAmelCase = [ 'module.fc.fc1.weight', 'module.fc.fc1.bias', 'module.fc.bn1.weight', 'module.fc.bn1.bias', 'module.fc.bn1.running_mean', 'module.fc.bn1.running_var', 'module.fc.bn1.num_batches_tracked', 'module.fc.fc2.weight', 'module.fc.fc2.bias', 'module.fc.bn2.weight', 'module.fc.bn2.bias', 'module.fc.bn2.running_mean', 'module.fc.bn2.running_var', 'module.fc.bn2.num_batches_tracked', 'module.fc.fc3.weight', 'module.fc.fc3.bias', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def lowerCAmelCase__ ( a__: str , a__: Optional[Any] , a__: Optional[Any] ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = dct.pop(a__ ) _UpperCAmelCase = val def lowerCAmelCase__ ( a__: Tuple , a__: List[str] ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = ViTMSNConfig() _UpperCAmelCase = 1_0_0_0 _UpperCAmelCase = 'datasets/huggingface/label-files' _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: _UpperCAmelCase = 3_8_4 _UpperCAmelCase = 1_5_3_6 _UpperCAmelCase = 6 elif "l16" in checkpoint_url: _UpperCAmelCase = 1_0_2_4 _UpperCAmelCase = 4_0_9_6 _UpperCAmelCase = 2_4 _UpperCAmelCase = 1_6 _UpperCAmelCase = 0.1 elif "b4" in checkpoint_url: _UpperCAmelCase = 4 elif "l7" in checkpoint_url: _UpperCAmelCase = 7 _UpperCAmelCase = 1_0_2_4 _UpperCAmelCase = 4_0_9_6 _UpperCAmelCase = 2_4 _UpperCAmelCase = 1_6 _UpperCAmelCase = 0.1 _UpperCAmelCase = ViTMSNModel(a__ ) _UpperCAmelCase = torch.hub.load_state_dict_from_url(a__ , map_location='cpu' )['target_encoder'] _UpperCAmelCase = ViTImageProcessor(size=config.image_size ) remove_projection_head(a__ ) _UpperCAmelCase = create_rename_keys(a__ , base_model=a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) read_in_q_k_v(a__ , a__ , base_model=a__ ) model.load_state_dict(a__ ) model.eval() _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) _UpperCAmelCase = ViTImageProcessor( size=config.image_size , image_mean=a__ , image_std=a__ ) _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ) # forward pass torch.manual_seed(2 ) _UpperCAmelCase = model(**a__ ) _UpperCAmelCase = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: _UpperCAmelCase = torch.tensor([[-1.0_915, -1.4_876, -1.1_809]] ) elif "b16" in checkpoint_url: _UpperCAmelCase = torch.tensor([[14.2_889, -18.9_045, 11.7_281]] ) elif "l16" in checkpoint_url: _UpperCAmelCase = torch.tensor([[41.5_028, -22.8_681, 45.6_475]] ) elif "b4" in checkpoint_url: _UpperCAmelCase = torch.tensor([[-4.3_868, 5.2_932, -0.4_137]] ) else: _UpperCAmelCase = torch.tensor([[-0.1_792, -0.6_465, 2.4_263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , a__ , atol=1e-4 ) print(F'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowerCAmelCase__ :int = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
329
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
1
from __future__ import annotations def lowerCAmelCase__ ( a__: int = 4 ) -> list[list[int]]: '''simple docstring''' _UpperCAmelCase = abs(a__ ) or 4 return [[1 + x + y * row_size for x in range(a__ )] for y in range(a__ )] def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' return reverse_row(transpose(a__ ) ) # OR.. transpose(reverse_column(matrix)) def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' return reverse_row(reverse_column(a__ ) ) # OR.. reverse_column(reverse_row(matrix)) def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' return reverse_column(transpose(a__ ) ) # OR.. transpose(reverse_row(matrix)) def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' _UpperCAmelCase = [list(a__ ) for x in zip(*a__ )] return matrix def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' _UpperCAmelCase = matrix[::-1] return matrix def lowerCAmelCase__ ( a__: list[list[int]] ) -> list[list[int]]: '''simple docstring''' _UpperCAmelCase = [x[::-1] for x in matrix] return matrix def lowerCAmelCase__ ( a__: list[list[int]] ) -> None: '''simple docstring''' for i in matrix: print(*a__ ) if __name__ == "__main__": lowerCAmelCase__ :Optional[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 90 counterclockwise:\n''') print_matrix(rotate_aa(matrix)) lowerCAmelCase__ :Union[str, Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 180:\n''') print_matrix(rotate_aaa(matrix)) lowerCAmelCase__ :List[Any] = make_matrix() print('''\norigin:\n''') print_matrix(matrix) print('''\nrotate 270 counterclockwise:\n''') print_matrix(rotate_aaa(matrix))
329
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
1
import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowerCAmelCase__ :List[Any] = logging.getLogger(__name__) def lowerCAmelCase__ ( a__: torch.nn.Module , a__: BnbQuantizationConfig , a__: Union[str, os.PathLike] = None , a__: Optional[Dict[str, Union[int, str, torch.device]]] = None , a__: Optional[List[str]] = None , a__: Optional[Dict[Union[int, str], Union[int, str]]] = None , a__: Optional[Union[str, os.PathLike]] = None , a__: bool = False , ) -> List[str]: '''simple docstring''' _UpperCAmelCase = bnb_quantization_config.load_in_abit _UpperCAmelCase = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( 'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,' ' make sure you have the latest version of `bitsandbytes` installed.' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( 'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,' 'make sure you have the latest version of `bitsandbytes` installed.' ) _UpperCAmelCase = [] # custom device map if isinstance(a__ , a__ ) and len(device_map.keys() ) > 1: _UpperCAmelCase = [key for key, value in device_map.items() if value in ['disk', 'cpu']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: _UpperCAmelCase = get_keys_to_not_convert(a__ ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(a__ ) _UpperCAmelCase = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: _UpperCAmelCase = [] _UpperCAmelCase = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(a__ ) # compatibility with peft _UpperCAmelCase = load_in_abit _UpperCAmelCase = load_in_abit _UpperCAmelCase = get_parameter_device(a__ ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( 'It is not recommended to quantize a loaded model. ' 'The model should be instantiated under the `init_empty_weights` context manager.' ) _UpperCAmelCase = replace_with_bnb_layers(a__ , a__ , modules_to_not_convert=a__ ) # convert param to the right dtype _UpperCAmelCase = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: _UpperCAmelCase = name.replace('.weight' , '' ).replace('.bias' , '' ) _UpperCAmelCase = getattr(a__ , a__ , a__ ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(a__ ): param.to(a__ ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info( F'''The model device type is {model_device.type}. However, cuda is needed for quantization.''' 'We move the model to cuda.' ) return model elif weights_location is None: raise RuntimeError( F'''`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ''' ) else: with init_empty_weights(): _UpperCAmelCase = replace_with_bnb_layers( a__ , a__ , modules_to_not_convert=a__ ) _UpperCAmelCase = get_quantized_model_device_map( a__ , a__ , a__ , max_memory=a__ , no_split_module_classes=a__ , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): _UpperCAmelCase = True _UpperCAmelCase = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] ) load_checkpoint_in_model( a__ , a__ , a__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=a__ , offload_state_dict=a__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(a__ , device_map=a__ , offload_dir=a__ ) def lowerCAmelCase__ ( a__: List[str] , a__: int , a__: str=None , a__: Optional[int]=None , a__: List[str]=None ) -> int: '''simple docstring''' if device_map is None: if torch.cuda.is_available(): _UpperCAmelCase = {'': torch.cuda.current_device()} else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.' ) if isinstance(a__ , a__ ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( 'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ' '\'sequential\'.' ) _UpperCAmelCase = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) _UpperCAmelCase = {} _UpperCAmelCase = special_dtypes _UpperCAmelCase = no_split_module_classes _UpperCAmelCase = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": _UpperCAmelCase = get_balanced_memory( a__ , low_zero=(device_map == 'balanced_low_0') , max_memory=a__ , **a__ , ) _UpperCAmelCase = max_memory _UpperCAmelCase = infer_auto_device_map(a__ , **a__ ) if isinstance(a__ , a__ ): # check if don't have any quantized module on the cpu _UpperCAmelCase = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules _UpperCAmelCase = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( '\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n ' ) else: logger.info( 'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit' ) del device_map_without_some_modules return device_map def lowerCAmelCase__ ( a__: Any , a__: Dict , a__: Union[str, Any]=None , a__: List[Any]=None ) -> List[str]: '''simple docstring''' if modules_to_not_convert is None: _UpperCAmelCase = [] _UpperCAmelCase , _UpperCAmelCase = _replace_with_bnb_layers( a__ , a__ , a__ , a__ ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def lowerCAmelCase__ ( a__: Union[str, Any] , a__: List[str] , a__: Dict=None , a__: Union[str, Any]=None , ) -> str: '''simple docstring''' _UpperCAmelCase = False for name, module in model.named_children(): if current_key_name is None: _UpperCAmelCase = [] current_key_name.append(a__ ) if isinstance(a__ , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` _UpperCAmelCase = '.'.join(a__ ) _UpperCAmelCase = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: _UpperCAmelCase = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: _UpperCAmelCase = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=a__ , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: _UpperCAmelCase = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('load_in_8bit and load_in_4bit can\'t be both False' ) _UpperCAmelCase = module.weight.data if module.bias is not None: _UpperCAmelCase = module.bias.data bnb_module.requires_grad_(a__ ) setattr(a__ , a__ , a__ ) _UpperCAmelCase = True if len(list(module.children() ) ) > 0: _UpperCAmelCase , _UpperCAmelCase = _replace_with_bnb_layers( a__ , a__ , a__ , a__ ) _UpperCAmelCase = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCAmelCase__ ( a__: Tuple ) -> int: '''simple docstring''' with init_empty_weights(): _UpperCAmelCase = deepcopy(a__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` _UpperCAmelCase = find_tied_parameters(a__ ) # For compatibility with Accelerate < 0.18 if isinstance(a__ , a__ ): _UpperCAmelCase = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: _UpperCAmelCase = sum(a__ , [] ) _UpperCAmelCase = len(a__ ) > 0 # Check if it is a base model _UpperCAmelCase = False if hasattr(a__ , 'base_model_prefix' ): _UpperCAmelCase = not hasattr(a__ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head _UpperCAmelCase = list(model.named_children() ) _UpperCAmelCase = [list_modules[-1][0]] # add last module together with tied weights _UpperCAmelCase = set(a__ ) - set(a__ ) _UpperCAmelCase = list(set(a__ ) ) + list(a__ ) # remove ".weight" from the keys _UpperCAmelCase = ['.weight', '.bias'] _UpperCAmelCase = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: _UpperCAmelCase = name.replace(a__ , '' ) filtered_module_names.append(a__ ) return filtered_module_names def lowerCAmelCase__ ( a__: Tuple ) -> Dict: '''simple docstring''' for m in model.modules(): if isinstance(a__ , bnb.nn.Linearabit ): return True return False def lowerCAmelCase__ ( a__: nn.Module ) -> Optional[Any]: '''simple docstring''' return next(parameter.parameters() ).device def lowerCAmelCase__ ( a__: List[str] , a__: Any , a__: str , a__: Union[str, Any] , a__: Optional[Any] , a__: Tuple , a__: Optional[Any] ) -> int: '''simple docstring''' if fpaa_statistics is None: set_module_tensor_to_device(a__ , a__ , 0 , dtype=a__ , value=a__ ) _UpperCAmelCase = param_name _UpperCAmelCase = model if "." in tensor_name: _UpperCAmelCase = tensor_name.split('.' ) for split in splits[:-1]: _UpperCAmelCase = getattr(a__ , a__ ) if new_module is None: raise ValueError(F'''{module} has no attribute {split}.''' ) _UpperCAmelCase = new_module _UpperCAmelCase = splits[-1] # offload weights _UpperCAmelCase = False offload_weight(module._parameters[tensor_name] , a__ , a__ , index=a__ ) if hasattr(module._parameters[tensor_name] , 'SCB' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , a__ , index=a__ , ) else: offload_weight(a__ , a__ , a__ , index=a__ ) offload_weight(a__ , param_name.replace('weight' , 'SCB' ) , a__ , index=a__ ) set_module_tensor_to_device(a__ , a__ , 'meta' , dtype=a__ , value=torch.empty(*param.size() ) )
329
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = AutoConfig.from_pretrained(a__ ) _UpperCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=a__ ) _UpperCAmelCase = checkpoints.load_tax_checkpoint(a__ ) _UpperCAmelCase = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": _UpperCAmelCase = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": _UpperCAmelCase = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['encoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_global_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = tax_mlp_layer_norm _UpperCAmelCase = flax_model_encoder_layer_block # Only for layer 0: _UpperCAmelCase = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_global_rel_embedding # Assigning _UpperCAmelCase = tax_model['target']['encoder']['encoder_norm']['scale'] _UpperCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] _UpperCAmelCase = tax_enc_dec_attention_module['key']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['out']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['query']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['decoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_pre_attention_layer_norm _UpperCAmelCase = tax_enc_dec_attention_key _UpperCAmelCase = tax_enc_dec_attention_out _UpperCAmelCase = tax_enc_dec_attention_query _UpperCAmelCase = tax_enc_dec_attention_value _UpperCAmelCase = tax_cross_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = txa_mlp_layer_norm _UpperCAmelCase = flax_model_decoder_layer_block # Decoder Normalization _UpperCAmelCase = tax_model['target']['decoder']['decoder_norm']['scale'] _UpperCAmelCase = txa_decoder_norm # Only for layer 0: _UpperCAmelCase = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_decoder_rel_embedding # Token Embeddings _UpperCAmelCase = tax_model['target']['token_embedder']['embedding'] _UpperCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: _UpperCAmelCase = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(a__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path the T5X checkpoint.''' ) parser.add_argument('''--config_name''', default=None, type=str, required=True, help='''Config name of LongT5/T5 model.''') parser.add_argument( '''--flax_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output FLAX model.''' ) lowerCAmelCase__ :List[str] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
329
1
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase__ ( a__: Optional[Any] , a__: Any , a__: Dict , a__: Optional[int] , a__: Optional[Any]=True , a__: Any="pt" ) -> int: '''simple docstring''' _UpperCAmelCase = {'add_prefix_space': True} if isinstance(a__ , a__ ) and not line.startswith(' ' ) else {} _UpperCAmelCase = padding_side return tokenizer( [line] , max_length=a__ , padding='max_length' if pad_to_max_length else None , truncation=a__ , return_tensors=a__ , add_special_tokens=a__ , **a__ , ) def lowerCAmelCase__ ( a__: Any , a__: Dict , a__: List[Any]=None , ) -> Tuple: '''simple docstring''' _UpperCAmelCase = input_ids.ne(a__ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="train" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="" , ) -> Dict: """simple docstring""" super().__init__() _UpperCAmelCase = Path(_SCREAMING_SNAKE_CASE ).joinpath(type_path + '.source' ) _UpperCAmelCase = Path(_SCREAMING_SNAKE_CASE ).joinpath(type_path + '.target' ) _UpperCAmelCase = self.get_char_lens(self.src_file ) _UpperCAmelCase = max_source_length _UpperCAmelCase = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' _UpperCAmelCase = tokenizer _UpperCAmelCase = prefix if n_obs is not None: _UpperCAmelCase = self.src_lens[:n_obs] _UpperCAmelCase = src_lang _UpperCAmelCase = tgt_lang def __len__( self ) -> List[str]: """simple docstring""" return len(self.src_lens ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict[str, torch.Tensor]: """simple docstring""" _UpperCAmelCase = index + 1 # linecache starts at 1 _UpperCAmelCase = self.prefix + linecache.getline(str(self.src_file ) , _SCREAMING_SNAKE_CASE ).rstrip('\n' ) _UpperCAmelCase = linecache.getline(str(self.tgt_file ) , _SCREAMING_SNAKE_CASE ).rstrip('\n' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right _UpperCAmelCase = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ) else self.tokenizer ) _UpperCAmelCase = self.tokenizer.generator if isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ) else self.tokenizer _UpperCAmelCase = encode_line(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.max_source_length , 'right' ) _UpperCAmelCase = encode_line(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.max_target_length , 'right' ) _UpperCAmelCase = source_inputs['input_ids'].squeeze() _UpperCAmelCase = target_inputs['input_ids'].squeeze() _UpperCAmelCase = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def UpperCAmelCase__ ( _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return [len(_SCREAMING_SNAKE_CASE ) for x in Path(_SCREAMING_SNAKE_CASE ).open().readlines()] def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict[str, torch.Tensor]: """simple docstring""" _UpperCAmelCase = torch.stack([x['input_ids'] for x in batch] ) _UpperCAmelCase = torch.stack([x['attention_mask'] for x in batch] ) _UpperCAmelCase = torch.stack([x['decoder_input_ids'] for x in batch] ) _UpperCAmelCase = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ) else self.tokenizer.pad_token_id ) _UpperCAmelCase = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _SCREAMING_SNAKE_CASE ) else self.tokenizer.pad_token_id ) _UpperCAmelCase = trim_batch(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = trim_batch(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch lowerCAmelCase__ :str = getLogger(__name__) def lowerCAmelCase__ ( a__: List[List] ) -> Tuple: '''simple docstring''' return list(itertools.chain.from_iterable(a__ ) ) def lowerCAmelCase__ ( a__: str ) -> None: '''simple docstring''' _UpperCAmelCase = get_git_info() save_json(a__ , os.path.join(a__ , 'git_log.json' ) ) def lowerCAmelCase__ ( a__: List[str] , a__: Dict , a__: Any=4 , **a__: Any ) -> List[Any]: '''simple docstring''' with open(a__ , 'w' ) as f: json.dump(a__ , a__ , indent=a__ , **a__ ) def lowerCAmelCase__ ( a__: Optional[Any] ) -> Tuple: '''simple docstring''' with open(a__ ) as f: return json.load(a__ ) def lowerCAmelCase__ ( ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = git.Repo(search_parent_directories=a__ ) _UpperCAmelCase = { 'repo_id': str(a__ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase__ ( a__: Callable , a__: Iterable ) -> List: '''simple docstring''' return list(map(a__ , a__ ) ) def lowerCAmelCase__ ( a__: Tuple , a__: Dict ) -> str: '''simple docstring''' with open(a__ , 'wb' ) as f: return pickle.dump(a__ , a__ ) def lowerCAmelCase__ ( a__: List[Any] ) -> Dict: '''simple docstring''' def remove_articles(a__: Dict ): return re.sub(R'\b(a|an|the)\b' , ' ' , a__ ) def white_space_fix(a__: int ): return " ".join(text.split() ) def remove_punc(a__: int ): _UpperCAmelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(a__: List[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(a__ ) ) ) ) def lowerCAmelCase__ ( a__: List[str] , a__: int ) -> Tuple: '''simple docstring''' _UpperCAmelCase = normalize_answer(a__ ).split() _UpperCAmelCase = normalize_answer(a__ ).split() _UpperCAmelCase = Counter(a__ ) & Counter(a__ ) _UpperCAmelCase = sum(common.values() ) if num_same == 0: return 0 _UpperCAmelCase = 1.0 * num_same / len(a__ ) _UpperCAmelCase = 1.0 * num_same / len(a__ ) _UpperCAmelCase = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase__ ( a__: Union[str, Any] , a__: Tuple ) -> List[Any]: '''simple docstring''' return normalize_answer(a__ ) == normalize_answer(a__ ) def lowerCAmelCase__ ( a__: List[str] , a__: List[str] ) -> Dict: '''simple docstring''' assert len(a__ ) == len(a__ ) _UpperCAmelCase = 0 for hypo, pred in zip(a__ , a__ ): em += exact_match_score(a__ , a__ ) if len(a__ ) > 0: em /= len(a__ ) return {"em": em} def lowerCAmelCase__ ( a__: List[str] ) -> int: '''simple docstring''' return model_prefix.startswith('rag' ) def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: List[Any] ) -> List[str]: '''simple docstring''' _UpperCAmelCase = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead _UpperCAmelCase = 'dropout_rate' for p in extra_params: if getattr(a__ , a__ , a__ ): if not hasattr(a__ , a__ ) and not hasattr(a__ , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(a__ ) ) delattr(a__ , a__ ) continue _UpperCAmelCase = p if hasattr(a__ , a__ ) else equivalent_param[p] setattr(a__ , a__ , getattr(a__ , a__ ) ) delattr(a__ , a__ ) return hparams, config
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : str = 'ctrl' _a : Tuple = ['past_key_values'] _a : List[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=246534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> Dict: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : str = DeformableDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DeformableDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = 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 , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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, ) , ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = DeformableDetrImageProcessor() _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = DeformableDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
329
1
import argparse import os import re import packaging.version lowerCAmelCase__ :Union[str, Any] = '''examples/''' lowerCAmelCase__ :Tuple = { '''examples''': (re.compile(R'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''), '''init''': (re.compile(R'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''), '''setup''': (re.compile(R'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), R'''\1version="VERSION",'''), '''doc''': (re.compile(R'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''), } lowerCAmelCase__ :str = { '''init''': '''src/transformers/__init__.py''', '''setup''': '''setup.py''', } lowerCAmelCase__ :Optional[int] = '''README.md''' def lowerCAmelCase__ ( a__: Tuple , a__: str , a__: List[Any] ) -> Dict: '''simple docstring''' with open(a__ , 'r' , encoding='utf-8' , newline='\n' ) as f: _UpperCAmelCase = f.read() _UpperCAmelCase , _UpperCAmelCase = REPLACE_PATTERNS[pattern] _UpperCAmelCase = replace.replace('VERSION' , a__ ) _UpperCAmelCase = re_pattern.sub(a__ , a__ ) with open(a__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(a__ ) def lowerCAmelCase__ ( a__: Any ) -> Optional[int]: '''simple docstring''' for folder, directories, fnames in os.walk(a__ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(a__ , a__ ) , a__ , pattern='examples' ) def lowerCAmelCase__ ( a__: Dict , a__: Optional[int]=False ) -> str: '''simple docstring''' for pattern, fname in REPLACE_FILES.items(): update_version_in_file(a__ , a__ , a__ ) if not patch: update_version_in_examples(a__ ) def lowerCAmelCase__ ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = '🤗 Transformers currently provides the following architectures' _UpperCAmelCase = '1. Want to contribute a new model?' with open(a__ , 'r' , encoding='utf-8' , newline='\n' ) as f: _UpperCAmelCase = f.readlines() # Find the start of the list. _UpperCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 _UpperCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): _UpperCAmelCase = lines[index].replace( 'https://huggingface.co/docs/transformers/main/model_doc' , 'https://huggingface.co/docs/transformers/model_doc' , ) index += 1 with open(a__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(a__ ) def lowerCAmelCase__ ( ) -> int: '''simple docstring''' with open(REPLACE_FILES['init'] , 'r' ) as f: _UpperCAmelCase = f.read() _UpperCAmelCase = REPLACE_PATTERNS['init'][0].search(a__ ).groups()[0] return packaging.version.parse(a__ ) def lowerCAmelCase__ ( a__: int=False ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: _UpperCAmelCase = default_version.base_version elif patch: _UpperCAmelCase = F'''{default_version.major}.{default_version.minor}.{default_version.micro + 1}''' else: _UpperCAmelCase = F'''{default_version.major}.{default_version.minor + 1}.0''' # Now let's ask nicely if that's the right one. _UpperCAmelCase = input(F'''Which version are you releasing? [{default_version}]''' ) if len(a__ ) == 0: _UpperCAmelCase = default_version print(F'''Updating version to {version}.''' ) global_version_update(a__ , patch=a__ ) if not patch: print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' _UpperCAmelCase = get_version() _UpperCAmelCase = F'''{current_version.major}.{current_version.minor + 1}.0.dev0''' _UpperCAmelCase = current_version.base_version # Check with the user we got that right. _UpperCAmelCase = input(F'''Which version are we developing now? [{dev_version}]''' ) if len(a__ ) == 0: _UpperCAmelCase = dev_version print(F'''Updating version to {version}.''' ) global_version_update(a__ ) print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() if __name__ == "__main__": lowerCAmelCase__ :Optional[Any] = argparse.ArgumentParser() parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''') parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''') lowerCAmelCase__ :List[str] = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print('''Nothing to do after a patch :-)''') else: post_release_work()
329
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a ( unittest.TestCase ): _a : List[str] = JukeboxTokenizer _a : List[Any] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
329
1
import warnings from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch from ...models import UNetaDModel from ...schedulers import RePaintScheduler from ...utils import PIL_INTERPOLATION, logging, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name def lowerCAmelCase__ ( a__: Union[List, PIL.Image.Image, torch.Tensor] ) -> Dict: '''simple docstring''' warnings.warn( 'The preprocess method is deprecated and will be removed in a future version. Please' ' use VaeImageProcessor.preprocess instead' , a__ , ) if isinstance(a__ , torch.Tensor ): return image elif isinstance(a__ , PIL.Image.Image ): _UpperCAmelCase = [image] if isinstance(image[0] , PIL.Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image[0].size _UpperCAmelCase , _UpperCAmelCase = (x - x % 8 for x in (w, h)) # resize to integer multiple of 8 _UpperCAmelCase = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] _UpperCAmelCase = np.concatenate(a__ , axis=0 ) _UpperCAmelCase = np.array(a__ ).astype(np.floataa ) / 255.0 _UpperCAmelCase = image.transpose(0 , 3 , 1 , 2 ) _UpperCAmelCase = 2.0 * image - 1.0 _UpperCAmelCase = torch.from_numpy(a__ ) elif isinstance(image[0] , torch.Tensor ): _UpperCAmelCase = torch.cat(a__ , dim=0 ) return image def lowerCAmelCase__ ( a__: Union[List, PIL.Image.Image, torch.Tensor] ) -> int: '''simple docstring''' if isinstance(a__ , torch.Tensor ): return mask elif isinstance(a__ , PIL.Image.Image ): _UpperCAmelCase = [mask] if isinstance(mask[0] , PIL.Image.Image ): _UpperCAmelCase , _UpperCAmelCase = mask[0].size _UpperCAmelCase , _UpperCAmelCase = (x - x % 3_2 for x in (w, h)) # resize to integer multiple of 32 _UpperCAmelCase = [np.array(m.convert('L' ).resize((w, h) , resample=PIL_INTERPOLATION['nearest'] ) )[None, :] for m in mask] _UpperCAmelCase = np.concatenate(a__ , axis=0 ) _UpperCAmelCase = mask.astype(np.floataa ) / 255.0 _UpperCAmelCase = 0 _UpperCAmelCase = 1 _UpperCAmelCase = torch.from_numpy(a__ ) elif isinstance(mask[0] , torch.Tensor ): _UpperCAmelCase = torch.cat(a__ , dim=0 ) return mask class __a ( UpperCAmelCase ): _a : UNetaDModel _a : RePaintScheduler def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() self.register_modules(unet=_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE ) @torch.no_grad() def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = 250 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = 10 , _SCREAMING_SNAKE_CASE = 10 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "pil" , _SCREAMING_SNAKE_CASE = True , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" _UpperCAmelCase = image _UpperCAmelCase = _preprocess_image(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = original_image.to(device=self.device , dtype=self.unet.dtype ) _UpperCAmelCase = _preprocess_mask(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = mask_image.to(device=self.device , dtype=self.unet.dtype ) _UpperCAmelCase = original_image.shape[0] # sample gaussian noise to begin the loop if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and len(_SCREAMING_SNAKE_CASE ) != batch_size: raise ValueError( f'''You have passed a list of generators of length {len(_SCREAMING_SNAKE_CASE )}, but requested an effective batch''' f''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' ) _UpperCAmelCase = original_image.shape _UpperCAmelCase = randn_tensor(_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , device=self.device , dtype=self.unet.dtype ) # set step values self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , self.device ) _UpperCAmelCase = eta _UpperCAmelCase = self.scheduler.timesteps[0] + 1 _UpperCAmelCase = generator[0] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else generator for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): if t < t_last: # predict the noise residual _UpperCAmelCase = self.unet(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).sample # compute previous image: x_t -> x_t-1 _UpperCAmelCase = self.scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).prev_sample else: # compute the reverse: x_t-1 -> x_t _UpperCAmelCase = self.scheduler.undo_step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = t _UpperCAmelCase = (image / 2 + 0.5).clamp(0 , 1 ) _UpperCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": _UpperCAmelCase = self.numpy_to_pil(_SCREAMING_SNAKE_CASE ) if not return_dict: return (image,) return ImagePipelineOutput(images=_SCREAMING_SNAKE_CASE )
329
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ :Optional[int] = logging.getLogger(__name__) def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = argparse.ArgumentParser( description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.' ) parser.add_argument( '--dataset_name' , type=a__ , default='wikitext' , help='Name of the training. Explore datasets at: hf.co/datasets.' , ) parser.add_argument( '--dataset_config' , type=a__ , default='wikitext-103-raw-v1' , help='Configuration name of the dataset.' ) parser.add_argument( '--tokenizer_name_or_path' , type=a__ , default='sayakpaul/unigram-tokenizer-wikitext' , help='Tokenizer identifier. Can be a local filepath or a Hub identifier.' , ) parser.add_argument( '--shard_size' , type=a__ , default=1_0_0_0 , help='Number of entries to go in a single shard.' , ) parser.add_argument('--split' , type=a__ , default='train' , choices=['train', 'test', 'validation'] ) parser.add_argument( '--limit' , default=a__ , type=a__ , help='Limit the number of shards (used for debugging).' , ) parser.add_argument( '--max_length' , type=a__ , default=5_1_2 , help='Maximum sequence length. For training on TPUs, it helps to have a maximum' ' sequence length that is a multiple of 8.' , ) parser.add_argument( '--output_dir' , default='tf-tpu' , type=a__ , help='Output directory where the TFRecord shards will be saved. If the' ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord' ' shards will be directly saved to a Google Cloud Storage bucket.' , ) _UpperCAmelCase = parser.parse_args() return args def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[Any]: '''simple docstring''' def fn(a__: str ): return tokenizer(examples['text'] ) return fn def lowerCAmelCase__ ( a__: List[str] ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for i in range(len(tokenized_data['input_ids'] ) ): _UpperCAmelCase = { 'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i] ) ), 'attention_mask': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i] ) ), } _UpperCAmelCase = tf.train.Features(feature=a__ ) _UpperCAmelCase = tf.train.Example(features=a__ ) _UpperCAmelCase = example.SerializeToString() records.append(a__ ) return records def lowerCAmelCase__ ( a__: Union[str, Any] ) -> int: '''simple docstring''' _UpperCAmelCase = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: _UpperCAmelCase = min(len(a__ ) , args.limit ) _UpperCAmelCase = dataset.select(range(a__ ) ) print(F'''Limiting the dataset to {args.limit} entries.''' ) _UpperCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _UpperCAmelCase = os.path.join(args.output_dir , args.split ) if not os.path.exists(a__ ): os.makedirs(a__ ) else: _UpperCAmelCase = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. _UpperCAmelCase = tokenize_function(a__ ) _UpperCAmelCase = dataset.map(a__ , batched=a__ , num_proc=4 , remove_columns=['text'] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(a__: Optional[int] ): # Concatenate all texts. _UpperCAmelCase = {k: sum(examples[k] , [] ) for k in examples.keys()} _UpperCAmelCase = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _UpperCAmelCase = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _UpperCAmelCase = { k: [t[i : i + args.max_length] for i in range(0 , a__ , args.max_length )] for k, t in concatenated_examples.items() } return result _UpperCAmelCase = dataset_tokenized.map(a__ , batched=a__ , batch_size=1_0_0_0 , num_proc=4 ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 for shard in range(0 , len(a__ ) , args.shard_size ): _UpperCAmelCase = grouped_dataset[shard : shard + args.shard_size] _UpperCAmelCase = len(dataset_snapshot['input_ids'] ) _UpperCAmelCase = os.path.join(a__ , F'''dataset-{shard_count}-{records_containing}.tfrecord''' ) _UpperCAmelCase = get_serialized_examples(a__ ) with tf.io.TFRecordWriter(a__ ) as out_file: for i in range(len(a__ ) ): _UpperCAmelCase = serialized_examples[i] out_file.write(a__ ) print('Wrote file {} containing {} records'.format(a__ , a__ ) ) shard_count += 1 total_records += records_containing with open(F'''split-{args.split}-records-count.txt''' , 'w' ) as f: print(F'''Total {args.split} records: {total_records}''' , file=a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = parse_args() main(args)
329
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_nllb import NllbTokenizer else: lowerCAmelCase__ :str = None lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''} lowerCAmelCase__ :Union[str, Any] = { '''vocab_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model''' ), }, '''tokenizer_file''': { '''facebook/nllb-200-distilled-600M''': ( '''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json''' ), }, } lowerCAmelCase__ :Union[str, Any] = { '''facebook/nllb-large-en-ro''': 1_0_2_4, '''facebook/nllb-200-distilled-600M''': 1_0_2_4, } # fmt: off lowerCAmelCase__ :Dict = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn'''] class __a ( UpperCAmelCase ): _a : List[Any] = VOCAB_FILES_NAMES _a : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _a : Any = ['input_ids', 'attention_mask'] _a : Dict = NllbTokenizer _a : List[int] = [] _a : List[int] = [] def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" _UpperCAmelCase = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token _UpperCAmelCase = legacy_behaviour super().__init__( vocab_file=_SCREAMING_SNAKE_CASE , tokenizer_file=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , src_lang=_SCREAMING_SNAKE_CASE , tgt_lang=_SCREAMING_SNAKE_CASE , additional_special_tokens=_SCREAMING_SNAKE_CASE , legacy_behaviour=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = vocab_file _UpperCAmelCase = False if not self.vocab_file else True _UpperCAmelCase = 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} ) _UpperCAmelCase = { lang_code: self.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) for lang_code in FAIRSEQ_LANGUAGE_CODES } _UpperCAmelCase = src_lang if src_lang is not None else 'eng_Latn' _UpperCAmelCase = self.convert_tokens_to_ids(self._src_lang ) _UpperCAmelCase = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" 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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) _UpperCAmelCase = src_lang _UpperCAmelCase = self(_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tgt_lang_id return inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "eng_Latn" , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "fra_Latn" , **_SCREAMING_SNAKE_CASE , ) -> BatchEncoding: """simple docstring""" _UpperCAmelCase = src_lang _UpperCAmelCase = tgt_lang return super().prepare_seqaseq_batch(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) if self.legacy_behaviour: _UpperCAmelCase = [] _UpperCAmelCase = [self.eos_token_id, self.cur_lang_code] else: _UpperCAmelCase = [self.cur_lang_code] _UpperCAmelCase = [self.eos_token_id] _UpperCAmelCase = self.convert_ids_to_tokens(self.prefix_tokens ) _UpperCAmelCase = self.convert_ids_to_tokens(self.suffix_tokens ) _UpperCAmelCase = 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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> None: """simple docstring""" _UpperCAmelCase = self.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) if self.legacy_behaviour: _UpperCAmelCase = [] _UpperCAmelCase = [self.eos_token_id, self.cur_lang_code] else: _UpperCAmelCase = [self.cur_lang_code] _UpperCAmelCase = [self.eos_token_id] _UpperCAmelCase = self.convert_ids_to_tokens(self.prefix_tokens ) _UpperCAmelCase = self.convert_ids_to_tokens(self.suffix_tokens ) _UpperCAmelCase = 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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory.''' ) return _UpperCAmelCase = 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,)
329
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any]=1_0 ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for _ in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCAmelCase__ ( a__: List[str] , a__: Any=1_0 ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [] for step in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(a__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , a__ ) _UpperCAmelCase = torch.load(a__ ) scheduler.load_state_dict(a__ ) return lrs @require_torch class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-3_0, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_SCREAMING_SNAKE_CASE , weight_decay=0.0 , relative_step=_SCREAMING_SNAKE_CASE , scale_parameter=_SCREAMING_SNAKE_CASE , warmup_init=_SCREAMING_SNAKE_CASE , ) for _ in range(1000 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __a ( unittest.TestCase ): _a : Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _a : Dict = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _a : List[Any] = 10 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE , msg=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListAlmostEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tol=1e-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_SCREAMING_SNAKE_CASE ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , msg=f'''failed for {scheduler_func} in save and reload''' ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = fn def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
329
1
import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class __a ( UpperCAmelCase ): _a : torch.FloatTensor _a : Optional[torch.FloatTensor] = None def lowerCAmelCase__ ( a__: Union[str, Any] , a__: Optional[int]=0.999 , a__: List[str]="cosine" , ) -> Union[str, Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(a__: Any ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a__: List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) _UpperCAmelCase = [] for i in range(a__ ): _UpperCAmelCase = i / num_diffusion_timesteps _UpperCAmelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a__ ) / alpha_bar_fn(a__ ) , a__ ) ) return torch.tensor(a__ , dtype=torch.floataa ) class __a ( UpperCAmelCase , UpperCAmelCase ): @register_to_config def __init__( self , _SCREAMING_SNAKE_CASE = 1000 , _SCREAMING_SNAKE_CASE = "fixed_small_log" , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1.0 , _SCREAMING_SNAKE_CASE = "epsilon" , _SCREAMING_SNAKE_CASE = "squaredcos_cap_v2" , ) -> List[Any]: """simple docstring""" if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'' ) _UpperCAmelCase = betas_for_alpha_bar(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 1.0 - self.betas _UpperCAmelCase = torch.cumprod(self.alphas , dim=0 ) _UpperCAmelCase = torch.tensor(1.0 ) # standard deviation of the initial noise distribution _UpperCAmelCase = 1.0 # setable values _UpperCAmelCase = None _UpperCAmelCase = torch.from_numpy(np.arange(0 , _SCREAMING_SNAKE_CASE )[::-1].copy() ) _UpperCAmelCase = variance_type def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> torch.FloatTensor: """simple docstring""" return sample def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = num_inference_steps _UpperCAmelCase = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) _UpperCAmelCase = (np.arange(0 , _SCREAMING_SNAKE_CASE ) * step_ratio).round()[::-1].copy().astype(np.intaa ) _UpperCAmelCase = torch.from_numpy(_SCREAMING_SNAKE_CASE ).to(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" if prev_timestep is None: _UpperCAmelCase = t - 1 _UpperCAmelCase = self.alphas_cumprod[t] _UpperCAmelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _UpperCAmelCase = 1 - alpha_prod_t _UpperCAmelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _UpperCAmelCase = self.betas[t] else: _UpperCAmelCase = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample _UpperCAmelCase = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: _UpperCAmelCase = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": _UpperCAmelCase = torch.log(torch.clamp(_SCREAMING_SNAKE_CASE , min=1e-2_0 ) ) _UpperCAmelCase = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler _UpperCAmelCase = variance.log() _UpperCAmelCase = beta.log() _UpperCAmelCase = (predicted_variance + 1) / 2 _UpperCAmelCase = frac * max_log + (1 - frac) * min_log return variance def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE = True , ) -> Union[UnCLIPSchedulerOutput, Tuple]: """simple docstring""" _UpperCAmelCase = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": _UpperCAmelCase , _UpperCAmelCase = torch.split(_SCREAMING_SNAKE_CASE , sample.shape[1] , dim=1 ) else: _UpperCAmelCase = None # 1. compute alphas, betas if prev_timestep is None: _UpperCAmelCase = t - 1 _UpperCAmelCase = self.alphas_cumprod[t] _UpperCAmelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one _UpperCAmelCase = 1 - alpha_prod_t _UpperCAmelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: _UpperCAmelCase = self.betas[t] _UpperCAmelCase = self.alphas[t] else: _UpperCAmelCase = 1 - alpha_prod_t / alpha_prod_t_prev _UpperCAmelCase = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": _UpperCAmelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": _UpperCAmelCase = model_output else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' ' for the UnCLIPScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: _UpperCAmelCase = torch.clamp( _SCREAMING_SNAKE_CASE , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCAmelCase = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t _UpperCAmelCase = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _UpperCAmelCase = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _UpperCAmelCase = 0 if t > 0: _UpperCAmelCase = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=_SCREAMING_SNAKE_CASE , device=model_output.device ) _UpperCAmelCase = self._get_variance( _SCREAMING_SNAKE_CASE , predicted_variance=_SCREAMING_SNAKE_CASE , prev_timestep=_SCREAMING_SNAKE_CASE , ) if self.variance_type == "fixed_small_log": _UpperCAmelCase = variance elif self.variance_type == "learned_range": _UpperCAmelCase = (0.5 * variance).exp() else: raise ValueError( f'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' ' for the UnCLIPScheduler.' ) _UpperCAmelCase = variance * variance_noise _UpperCAmelCase = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=_SCREAMING_SNAKE_CASE , pred_original_sample=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) -> torch.FloatTensor: """simple docstring""" _UpperCAmelCase = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) _UpperCAmelCase = timesteps.to(original_samples.device ) _UpperCAmelCase = alphas_cumprod[timesteps] ** 0.5 _UpperCAmelCase = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): _UpperCAmelCase = sqrt_alpha_prod.unsqueeze(-1 ) _UpperCAmelCase = (1 - alphas_cumprod[timesteps]) ** 0.5 _UpperCAmelCase = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): _UpperCAmelCase = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) _UpperCAmelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
329
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Any = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any] , a__: Dict , a__: Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = original_name.split('.' )[0] _UpperCAmelCase = key.split('.' ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 2] ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 1] ) _UpperCAmelCase = orig_block_num - offset _UpperCAmelCase = key.replace(F'''{orig_block_num}.{layer_num}.{original_name}''' , F'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def lowerCAmelCase__ ( a__: Tuple ) -> int: '''simple docstring''' _UpperCAmelCase = OrderedDict() _UpperCAmelCase , _UpperCAmelCase = 0, 0 for key, value in state_dict.items(): if key.startswith('network' ): _UpperCAmelCase = key.replace('network' , 'poolformer.encoder' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('bias' ) and "patch_embed" not in key: patch_emb_offset += 1 _UpperCAmelCase = key[: key.find('proj' )] _UpperCAmelCase = key.replace(a__ , F'''patch_embeddings.{total_embed_found}.''' ) _UpperCAmelCase = key.replace('proj' , 'projection' ) if key.endswith('bias' ): total_embed_found += 1 if "patch_embeddings" in key: _UpperCAmelCase = 'poolformer.encoder.' + key if "mlp.fc1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc1' , 'output.conv1' ) if "mlp.fc2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc2' , 'output.conv2' ) if "norm1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm1' , 'before_norm' ) if "norm2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm2' , 'after_norm' ) if "layer_scale_1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_1' , 'layer_scale_1' ) if "layer_scale_2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_2' , 'layer_scale_2' ) if "head" in key: _UpperCAmelCase = key.replace('head' , 'classifier' ) _UpperCAmelCase = value return new_state_dict def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return image @torch.no_grad() def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: Any ) -> Dict: '''simple docstring''' _UpperCAmelCase = PoolFormerConfig() # set attributes based on model_name _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = model_name[-3:] _UpperCAmelCase = 1_0_0_0 _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = (1, 1_0_0_0) # set config attributes _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} if size == "s12": _UpperCAmelCase = [2, 2, 6, 2] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s24": _UpperCAmelCase = [4, 4, 1_2, 4] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.9 elif size == "m36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 elif size == "m48": _UpperCAmelCase = [8, 8, 2_4, 8] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 else: raise ValueError(F'''Size {size} not supported''' ) # load image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) # Prepare image _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) # rename keys _UpperCAmelCase = rename_keys(a__ ) # create HuggingFace model and load state dict _UpperCAmelCase = PoolFormerForImageClassification(a__ ) model.load_state_dict(a__ ) model.eval() # Define image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values # forward pass _UpperCAmelCase = model(a__ ) _UpperCAmelCase = outputs.logits # define expected logit slices for different models if size == "s12": _UpperCAmelCase = torch.tensor([-0.3_045, -0.6_758, -0.4_869] ) elif size == "s24": _UpperCAmelCase = torch.tensor([0.4_402, -0.1_374, -0.8_045] ) elif size == "s36": _UpperCAmelCase = torch.tensor([-0.6_080, -0.5_133, -0.5_898] ) elif size == "m36": _UpperCAmelCase = torch.tensor([0.3_952, 0.2_263, -1.2_668] ) elif size == "m48": _UpperCAmelCase = torch.tensor([0.1_167, -0.0_656, -0.3_423] ) else: raise ValueError(F'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , a__ , atol=1e-2 ) # finally, save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(a__ ).mkdir(exist_ok=a__ ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
329
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :Dict = { '''configuration_instructblip''': [ '''INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''InstructBlipConfig''', '''InstructBlipQFormerConfig''', '''InstructBlipVisionConfig''', ], '''processing_instructblip''': ['''InstructBlipProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Dict = [ '''INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''InstructBlipQFormerModel''', '''InstructBlipPreTrainedModel''', '''InstructBlipForConditionalGeneration''', '''InstructBlipVisionModel''', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys lowerCAmelCase__ :List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = process _UpperCAmelCase = params def __len__( self ) -> Union[str, Any]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = self.dataset[i] _UpperCAmelCase = self.process(_SCREAMING_SNAKE_CASE , **self.params ) return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = loader _UpperCAmelCase = infer _UpperCAmelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether _UpperCAmelCase = None _UpperCAmelCase = loader_batch_size # Internal bookkeeping _UpperCAmelCase = None _UpperCAmelCase = None def __len__( self ) -> Any: """simple docstring""" return len(self.loader ) def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice _UpperCAmelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) _UpperCAmelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Convert ModelOutput to tuple first _UpperCAmelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around _UpperCAmelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. _UpperCAmelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 _UpperCAmelCase = self._loader_batch_data.__class__(_SCREAMING_SNAKE_CASE ) self._loader_batch_index += 1 return result def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch _UpperCAmelCase = next(self.iterator ) _UpperCAmelCase = self.infer(_SCREAMING_SNAKE_CASE , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size # Setting internal index to unwrap the batch _UpperCAmelCase = processed _UpperCAmelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __iter__( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) _UpperCAmelCase = None return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if self.subiterator is None: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item _UpperCAmelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) _UpperCAmelCase = next(self.subiterator ) return processed class __a ( UpperCAmelCase ): def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = False _UpperCAmelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator while not is_last: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size _UpperCAmelCase = processed _UpperCAmelCase = 0 while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator else: _UpperCAmelCase = processed _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) return accumulator class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = key def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return self.dataset[i][self.key] class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = keya _UpperCAmelCase = keya def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
329
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCAmelCase__ :List[str] = { '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys lowerCAmelCase__ :Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __a ( UpperCAmelCase ): _a : str = 'data2vec-text' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = position_embedding_type _UpperCAmelCase = use_cache _UpperCAmelCase = classifier_dropout class __a ( UpperCAmelCase ): @property def UpperCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
329
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase__ :List[Any] = { '''configuration_mobilevit''': ['''MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MobileViTConfig''', '''MobileViTOnnxConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :List[Any] = ['''MobileViTFeatureExtractor'''] lowerCAmelCase__ :Dict = ['''MobileViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :List[str] = [ '''MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MobileViTForImageClassification''', '''MobileViTForSemanticSegmentation''', '''MobileViTModel''', '''MobileViTPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :int = [ '''TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFMobileViTForImageClassification''', '''TFMobileViTForSemanticSegmentation''', '''TFMobileViTModel''', '''TFMobileViTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mobilevit import MOBILEVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileViTConfig, MobileViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_mobilevit import MobileViTFeatureExtractor from .image_processing_mobilevit import MobileViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilevit import ( MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel, MobileViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilevit import ( TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel, TFMobileViTPreTrainedModel, ) else: import sys lowerCAmelCase__ :Tuple = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> List[str]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = depths _UpperCAmelCase = num_heads _UpperCAmelCase = window_size _UpperCAmelCase = mlp_ratio _UpperCAmelCase = qkv_bias _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = hidden_act _UpperCAmelCase = use_absolute_embeddings _UpperCAmelCase = patch_norm _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = is_training _UpperCAmelCase = scope _UpperCAmelCase = use_labels _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = encoder_stride _UpperCAmelCase = out_features _UpperCAmelCase = out_indices def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _UpperCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = ['stem'] _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _a : str = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} _a : Optional[int] = False _a : List[str] = False _a : List[str] = False _a : Optional[int] = False _a : Tuple = False def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip('Swin does not use inputs_embeds' ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" pass @unittest.skip('Swin does not support feedforward chunking' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = 3 _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _UpperCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has''' f''' `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}.''' ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) @require_torch class __a ( unittest.TestCase , UpperCAmelCase ): _a : Any = (MaskFormerSwinBackbone,) if is_torch_available() else () _a : Any = MaskFormerSwinConfig def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: _UpperCAmelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
329
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
from collections.abc import Generator def lowerCAmelCase__ ( ) -> Generator[int, None, None]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = 0, 1 while True: _UpperCAmelCase , _UpperCAmelCase = b, a + b yield b def lowerCAmelCase__ ( a__: int = 1_0_0_0 ) -> int: '''simple docstring''' _UpperCAmelCase = 1 _UpperCAmelCase = fibonacci_generator() while len(str(next(a__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
329
1
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def lowerCAmelCase__ ( a__: int ) -> List[str]: '''simple docstring''' def is_in_circle(a__: float , a__: float ) -> bool: _UpperCAmelCase = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle _UpperCAmelCase = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(a__ ) ) # The ratio of the area for circle to square is pi/4. _UpperCAmelCase = proportion * 4 print(F'''The estimated value of pi is {pi_estimate}''' ) print(F'''The numpy value of pi is {pi}''' ) print(F'''The total error is {abs(pi - pi_estimate )}''' ) def lowerCAmelCase__ ( a__: int , a__: Callable[[float], float] , a__: float = 0.0 , a__: float = 1.0 , ) -> float: '''simple docstring''' return mean( function_to_integrate(uniform(a__ , a__ ) ) for _ in range(a__ ) ) * (max_value - min_value) def lowerCAmelCase__ ( a__: int , a__: float = 0.0 , a__: float = 1.0 ) -> None: '''simple docstring''' def identity_function(a__: float ) -> float: return x _UpperCAmelCase = area_under_curve_estimator( a__ , a__ , a__ , a__ ) _UpperCAmelCase = (max_value * max_value - min_value * min_value) / 2 print('******************' ) print(F'''Estimating area under y=x where x varies from {min_value} to {max_value}''' ) print(F'''Estimated value is {estimated_value}''' ) print(F'''Expected value is {expected_value}''' ) print(F'''Total error is {abs(estimated_value - expected_value )}''' ) print('******************' ) def lowerCAmelCase__ ( a__: int ) -> None: '''simple docstring''' def function_to_integrate(a__: float ) -> float: return sqrt(4.0 - x * x ) _UpperCAmelCase = area_under_curve_estimator( a__ , a__ , 0.0 , 2.0 ) print('******************' ) print('Estimating pi using area_under_curve_estimator' ) print(F'''Estimated value is {estimated_value}''' ) print(F'''Expected value is {pi}''' ) print(F'''Total error is {abs(estimated_value - pi )}''' ) print('******************' ) if __name__ == "__main__": import doctest doctest.testmod()
329
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
1
from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = "geglu" , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = "layer_norm" , _SCREAMING_SNAKE_CASE = False , ) -> List[str]: """simple docstring""" super().__init__() _UpperCAmelCase = only_cross_attention _UpperCAmelCase = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm_zero' _UpperCAmelCase = (num_embeds_ada_norm is not None) and norm_type == 'ada_norm' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( f'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to''' f''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: _UpperCAmelCase = AdaLayerNorm(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.use_ada_layer_norm_zero: _UpperCAmelCase = AdaLayerNormZero(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = Attention( query_dim=_SCREAMING_SNAKE_CASE , heads=_SCREAMING_SNAKE_CASE , dim_head=_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_SCREAMING_SNAKE_CASE , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. _UpperCAmelCase = ( AdaLayerNorm(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm else nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = Attention( query_dim=_SCREAMING_SNAKE_CASE , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_SCREAMING_SNAKE_CASE , dim_head=_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , bias=_SCREAMING_SNAKE_CASE , upcast_attention=_SCREAMING_SNAKE_CASE , ) # is self-attn if encoder_hidden_states is none else: _UpperCAmelCase = None _UpperCAmelCase = None # 3. Feed-forward _UpperCAmelCase = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = FeedForward(_SCREAMING_SNAKE_CASE , dropout=_SCREAMING_SNAKE_CASE , activation_fn=_SCREAMING_SNAKE_CASE , final_dropout=_SCREAMING_SNAKE_CASE ) # let chunk size default to None _UpperCAmelCase = None _UpperCAmelCase = 0 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = chunk_size _UpperCAmelCase = dim def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , ) -> Any: """simple docstring""" if self.use_ada_layer_norm: _UpperCAmelCase = self.norma(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif self.use_ada_layer_norm_zero: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = self.norma( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hidden_dtype=hidden_states.dtype ) else: _UpperCAmelCase = self.norma(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = cross_attention_kwargs if cross_attention_kwargs is not None else {} _UpperCAmelCase = self.attna( _SCREAMING_SNAKE_CASE , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) if self.use_ada_layer_norm_zero: _UpperCAmelCase = gate_msa.unsqueeze(1 ) * attn_output _UpperCAmelCase = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: _UpperCAmelCase = ( self.norma(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm else self.norma(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = self.attna( _SCREAMING_SNAKE_CASE , encoder_hidden_states=_SCREAMING_SNAKE_CASE , attention_mask=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = attn_output + hidden_states # 3. Feed-forward _UpperCAmelCase = self.norma(_SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm_zero: _UpperCAmelCase = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( f'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''' ) _UpperCAmelCase = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size _UpperCAmelCase = torch.cat( [self.ff(_SCREAMING_SNAKE_CASE ) for hid_slice in norm_hidden_states.chunk(_SCREAMING_SNAKE_CASE , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: _UpperCAmelCase = self.ff(_SCREAMING_SNAKE_CASE ) if self.use_ada_layer_norm_zero: _UpperCAmelCase = gate_mlp.unsqueeze(1 ) * ff_output _UpperCAmelCase = ff_output + hidden_states return hidden_states class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 4 , _SCREAMING_SNAKE_CASE = 0.0 , _SCREAMING_SNAKE_CASE = "geglu" , _SCREAMING_SNAKE_CASE = False , ) -> Optional[Any]: """simple docstring""" super().__init__() _UpperCAmelCase = int(dim * mult ) _UpperCAmelCase = dim_out if dim_out is not None else dim if activation_fn == "gelu": _UpperCAmelCase = GELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if activation_fn == "gelu-approximate": _UpperCAmelCase = GELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , approximate='tanh' ) elif activation_fn == "geglu": _UpperCAmelCase = GEGLU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif activation_fn == "geglu-approximate": _UpperCAmelCase = ApproximateGELU(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = nn.ModuleList([] ) # project in self.net.append(_SCREAMING_SNAKE_CASE ) # project dropout self.net.append(nn.Dropout(_SCREAMING_SNAKE_CASE ) ) # project out self.net.append(nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(_SCREAMING_SNAKE_CASE ) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" for module in self.net: _UpperCAmelCase = module(_SCREAMING_SNAKE_CASE ) return hidden_states class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "none" ) -> Tuple: """simple docstring""" super().__init__() _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = approximate def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" if gate.device.type != "mps": return F.gelu(_SCREAMING_SNAKE_CASE , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = self.proj(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.gelu(_SCREAMING_SNAKE_CASE ) return hidden_states class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" super().__init__() _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , dim_out * 2 ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" if gate.device.type != "mps": return F.gelu(_SCREAMING_SNAKE_CASE ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.proj(_SCREAMING_SNAKE_CASE ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(_SCREAMING_SNAKE_CASE ) class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" super().__init__() _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.proj(_SCREAMING_SNAKE_CASE ) return x * torch.sigmoid(1.702 * x ) class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" super().__init__() _UpperCAmelCase = nn.Embedding(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = nn.SiLU() _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , embedding_dim * 2 ) _UpperCAmelCase = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = self.linear(self.silu(self.emb(_SCREAMING_SNAKE_CASE ) ) ) _UpperCAmelCase , _UpperCAmelCase = torch.chunk(_SCREAMING_SNAKE_CASE , 2 ) _UpperCAmelCase = self.norm(_SCREAMING_SNAKE_CASE ) * (1 + scale) + shift return x class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__() _UpperCAmelCase = CombinedTimestepLabelEmbeddings(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = nn.SiLU() _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , 6 * embedding_dim , bias=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = nn.LayerNorm(_SCREAMING_SNAKE_CASE , elementwise_affine=_SCREAMING_SNAKE_CASE , eps=1e-6 ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = self.linear(self.silu(self.emb(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , hidden_dtype=_SCREAMING_SNAKE_CASE ) ) ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = emb.chunk(6 , dim=1 ) _UpperCAmelCase = self.norm(_SCREAMING_SNAKE_CASE ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class __a ( nn.Module ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = 1e-5 ) -> Optional[Any]: """simple docstring""" super().__init__() _UpperCAmelCase = num_groups _UpperCAmelCase = eps if act_fn is None: _UpperCAmelCase = None else: _UpperCAmelCase = get_activation(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = nn.Linear(_SCREAMING_SNAKE_CASE , out_dim * 2 ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" if self.act: _UpperCAmelCase = self.act(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.linear(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = emb[:, :, None, None] _UpperCAmelCase , _UpperCAmelCase = emb.chunk(2 , dim=1 ) _UpperCAmelCase = F.group_norm(_SCREAMING_SNAKE_CASE , self.num_groups , eps=self.eps ) _UpperCAmelCase = x * (1 + scale) + shift return x
329
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 20} _UpperCAmelCase = do_thumbnail _UpperCAmelCase = do_align_axis _UpperCAmelCase = do_pad _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = DonutImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DonutImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 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 , 'do_thumbnail' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_align_long_axis' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , )
329
1
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase__ :str = '''https://openaipublic.azureedge.net/jukebox/models/''' lowerCAmelCase__ :Optional[Any] = { '''jukebox-1b-lyrics''': [ '''5b/vqvae.pth.tar''', '''5b/prior_level_0.pth.tar''', '''5b/prior_level_1.pth.tar''', '''1b_lyrics/prior_level_2.pth.tar''', ], '''jukebox-5b-lyrics''': [ '''5b/vqvae.pth.tar''', '''5b/prior_level_0.pth.tar''', '''5b/prior_level_1.pth.tar''', '''5b_lyrics/prior_level_2.pth.tar''', ], } def lowerCAmelCase__ ( a__: Tuple ) -> Dict: '''simple docstring''' if key.endswith('.model.1.bias' ) and len(key.split('.' ) ) > 1_0: _UpperCAmelCase = key.replace('.model.1.bias' , '.conv1d_1.bias' ) elif key.endswith('.model.1.weight' ) and len(key.split('.' ) ) > 1_0: _UpperCAmelCase = key.replace('.model.1.weight' , '.conv1d_1.weight' ) elif key.endswith('.model.3.bias' ) and len(key.split('.' ) ) > 1_0: _UpperCAmelCase = key.replace('.model.3.bias' , '.conv1d_2.bias' ) elif key.endswith('.model.3.weight' ) and len(key.split('.' ) ) > 1_0: _UpperCAmelCase = key.replace('.model.3.weight' , '.conv1d_2.weight' ) if "conditioner_blocks.0." in key: _UpperCAmelCase = key.replace('conditioner_blocks.0' , 'conditioner_blocks' ) if "prime_prior" in key: _UpperCAmelCase = key.replace('prime_prior' , 'encoder' ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: _UpperCAmelCase = key.replace('.emb.' , '.' ) if key.endswith('k' ): # replace vqvae.X.k with vqvae.X.codebook return key.replace('.k' , '.codebook' ) if "y_emb." in key: return key.replace('y_emb.' , 'metadata_embedding.' ) if "x_emb.emb." in key: _UpperCAmelCase = key.replace('0.x_emb.emb' , 'embed_tokens' ) if "prime_state_ln" in key: return key.replace('prime_state_ln' , 'encoder.final_layer_norm' ) if ".ln" in key: return key.replace('.ln' , '.layer_norm' ) if "_ln" in key: return key.replace('_ln' , '_layer_norm' ) if "prime_state_proj" in key: return key.replace('prime_state_proj' , 'encoder.proj_in' ) if "prime_x_out" in key: return key.replace('prime_x_out' , 'encoder.lm_head' ) if "prior.x_out" in key: return key.replace('x_out' , 'fc_proj_out' ) if "x_emb" in key: return key.replace('x_emb' , 'embed_tokens' ) return key def lowerCAmelCase__ ( a__: Tuple , a__: Dict , a__: int , a__: int ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = {} import re _UpperCAmelCase = re.compile(R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)' ) _UpperCAmelCase = re.compile( R'conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) _UpperCAmelCase = re.compile(R'conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)' ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(a__ ): _UpperCAmelCase = re_encoder_block_conv_in.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCAmelCase = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' _UpperCAmelCase = re_encoder_block_conv_in.sub(a__ , a__ ) elif re_encoder_block_resnet.fullmatch(a__ ): _UpperCAmelCase = re_encoder_block_resnet.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' _UpperCAmelCase = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_encoder_block_resnet.sub(a__ , a__ ) elif re_encoder_block_proj_out.fullmatch(a__ ): _UpperCAmelCase = re_encoder_block_proj_out.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' _UpperCAmelCase = re_encoder_block_proj_out.sub(a__ , a__ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(a__ ): _UpperCAmelCase = re_decoder_block_conv_out.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCAmelCase = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' _UpperCAmelCase = re_decoder_block_conv_out.sub(a__ , a__ ) elif re_decoder_block_resnet.fullmatch(a__ ): _UpperCAmelCase = re_decoder_block_resnet.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[2] ) * 2 + int(groups[3] ) - 2 _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' _UpperCAmelCase = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_decoder_block_resnet.sub(a__ , a__ ) elif re_decoder_block_proj_in.fullmatch(a__ ): _UpperCAmelCase = re_decoder_block_proj_in.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' _UpperCAmelCase = re_decoder_block_proj_in.sub(a__ , a__ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(a__ ): _UpperCAmelCase = re_prior_cond_conv_out.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCAmelCase = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' _UpperCAmelCase = re_prior_cond_conv_out.sub(a__ , a__ ) elif re_prior_cond_resnet.fullmatch(a__ ): _UpperCAmelCase = re_prior_cond_resnet.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = int(groups[1] ) * 2 + int(groups[2] ) - 2 _UpperCAmelCase = {'1': 1, '3': 2}[groups[-2]] _UpperCAmelCase = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' _UpperCAmelCase = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' _UpperCAmelCase = prefix + resnet_block _UpperCAmelCase = re_prior_cond_resnet.sub(a__ , a__ ) elif re_prior_cond_proj_in.fullmatch(a__ ): _UpperCAmelCase = re_prior_cond_proj_in.match(a__ ) _UpperCAmelCase = regex_match.groups() _UpperCAmelCase = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' _UpperCAmelCase = re_prior_cond_proj_in.sub(a__ , a__ ) # keep original key else: _UpperCAmelCase = original_key _UpperCAmelCase = replace_key(a__ ) if F'''{key_prefix}.{key}''' not in model_state_dict or key is None: print(F'''failed converting {original_key} to {key}, does not match''' ) # handle missmatched shape elif value.shape != model_state_dict[F'''{key_prefix}.{key}'''].shape: _UpperCAmelCase = model_state_dict[F'''{key_prefix}.{key}'''] print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) _UpperCAmelCase = original_key _UpperCAmelCase = original_key _UpperCAmelCase = value return new_dict @torch.no_grad() def lowerCAmelCase__ ( a__: Tuple=None , a__: Any=None ) -> Tuple: '''simple docstring''' for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): _UpperCAmelCase = requests.get(F'''{PREFIX}{file}''' , allow_redirects=a__ ) os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=a__ ) open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , 'wb' ).write(r.content ) _UpperCAmelCase = MODEL_MAPPING[model_name.split('/' )[-1]] _UpperCAmelCase = JukeboxConfig.from_pretrained(a__ ) _UpperCAmelCase = JukeboxModel(a__ ) _UpperCAmelCase = [] _UpperCAmelCase = {} for i, dict_name in enumerate(a__ ): _UpperCAmelCase = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )['model'] _UpperCAmelCase = {} for k in old_dic.keys(): if k.endswith('.b' ): _UpperCAmelCase = old_dic[k] elif k.endswith('.w' ): _UpperCAmelCase = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: _UpperCAmelCase = old_dic[k] else: _UpperCAmelCase = old_dic[k] _UpperCAmelCase = 'vqvae' if i == 0 else F'''priors.{3 - i}''' _UpperCAmelCase = fix_jukebox_keys(a__ , model.state_dict() , a__ , a__ ) weight_dict.append(a__ ) _UpperCAmelCase = weight_dict.pop(0 ) model.vqvae.load_state_dict(a__ ) for i in range(len(a__ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(a__ ).mkdir(exist_ok=a__ ) with open(F'''{pytorch_dump_folder_path}/mapping.json''' , 'w' ) as txtfile: json.dump(a__ , a__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(a__ ) return weight_dict if __name__ == "__main__": lowerCAmelCase__ :str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''jukebox-5b-lyrics''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''jukebox-5b-lyrics-converted''', type=str, help='''Path to the output PyTorch model directory.''', ) lowerCAmelCase__ :Any = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('''.''') def lowerCAmelCase__ ( a__: Tuple ) -> str: '''simple docstring''' _UpperCAmelCase = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F'''{test_file} instead.''' ) _UpperCAmelCase = components[-1] if not test_fn.endswith('py' ): raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.''' ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.''' ) _UpperCAmelCase = components[:-1] + [test_fn.replace('.py' , '' )] _UpperCAmelCase = '.'.join(a__ ) return test_module_path def lowerCAmelCase__ ( a__: str ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = get_module_path(a__ ) _UpperCAmelCase = importlib.import_module(a__ ) return test_module def lowerCAmelCase__ ( a__: Any ) -> int: '''simple docstring''' _UpperCAmelCase = [] _UpperCAmelCase = get_test_module(a__ ) for attr in dir(a__ ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(a__ , a__ ) ) # sort with class names return sorted(a__ , key=lambda a__ : x.__name__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = [] _UpperCAmelCase = get_test_module(a__ ) for attr in dir(a__ ): _UpperCAmelCase = getattr(a__ , a__ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). _UpperCAmelCase = getattr(a__ , 'all_model_classes' , [] ) if len(a__ ) > 0: test_classes.append(a__ ) # sort with class names return sorted(a__ , key=lambda a__ : x.__name__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[str]: '''simple docstring''' _UpperCAmelCase = get_test_classes(a__ ) _UpperCAmelCase = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(a__ , key=lambda a__ : x.__name__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> Dict: '''simple docstring''' _UpperCAmelCase = test_class() if hasattr(a__ , 'setUp' ): test.setUp() _UpperCAmelCase = None if hasattr(a__ , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: _UpperCAmelCase = test.model_tester.__class__ return model_tester def lowerCAmelCase__ ( a__: str , a__: Any ) -> str: '''simple docstring''' _UpperCAmelCase = get_test_classes(a__ ) _UpperCAmelCase = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(a__ ) # sort with class names return sorted(a__ , key=lambda a__ : x.__name__ ) def lowerCAmelCase__ ( a__: str , a__: Union[str, Any] ) -> Any: '''simple docstring''' _UpperCAmelCase = get_test_classes_for_model(a__ , a__ ) _UpperCAmelCase = [] for test_class in test_classes: _UpperCAmelCase = get_model_tester_from_test_class(a__ ) if tester_class is not None: tester_classes.append(a__ ) # sort with class names return sorted(a__ , key=lambda a__ : x.__name__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> int: '''simple docstring''' _UpperCAmelCase = get_test_classes(a__ ) _UpperCAmelCase = {test_class: get_model_tester_from_test_class(a__ ) for test_class in test_classes} return test_tester_mapping def lowerCAmelCase__ ( a__: int ) -> int: '''simple docstring''' _UpperCAmelCase = get_model_classes(a__ ) _UpperCAmelCase = { model_class: get_test_classes_for_model(a__ , a__ ) for model_class in model_classes } return model_test_mapping def lowerCAmelCase__ ( a__: Dict ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = get_model_classes(a__ ) _UpperCAmelCase = { model_class: get_tester_classes_for_model(a__ , a__ ) for model_class in model_classes } return model_to_tester_mapping def lowerCAmelCase__ ( a__: Optional[int] ) -> str: '''simple docstring''' if isinstance(a__ , a__ ): return o elif isinstance(a__ , a__ ): return o.__name__ elif isinstance(a__ , (list, tuple) ): return [to_json(a__ ) for x in o] elif isinstance(a__ , a__ ): return {to_json(a__ ): to_json(a__ ) for k, v in o.items()} else: return o
329
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
1
import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) 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 ): _a : Optional[Any] = KandinskyVaaControlnetPipeline _a : Optional[Any] = ['image_embeds', 'negative_image_embeds', 'hint'] _a : List[str] = ['image_embeds', 'negative_image_embeds', 'hint'] _a : Tuple = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] _a : List[Any] = False @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return 32 @property def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" return self.time_input_dim @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return self.time_input_dim * 4 @property def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" return 100 @property def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = { 'in_channels': 8, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image_hint', '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, } _UpperCAmelCase = UNetaDConditionModel(**_SCREAMING_SNAKE_CASE ) return model @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return { "block_out_channels": [32, 32, 64, 64], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "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", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) _UpperCAmelCase = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.dummy_unet _UpperCAmelCase = self.dummy_movq _UpperCAmelCase = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='linear' , beta_start=0.00085 , beta_end=0.012 , clip_sample=_SCREAMING_SNAKE_CASE , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , prediction_type='epsilon' , thresholding=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> Dict: """simple docstring""" _UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _SCREAMING_SNAKE_CASE ) # create hint _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(_SCREAMING_SNAKE_CASE ) ).to(_SCREAMING_SNAKE_CASE ) if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'hint': hint, 'generator': generator, 'height': 64, 'width': 64, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 'cpu' _UpperCAmelCase = self.get_dummy_components() _UpperCAmelCase = self.pipeline_class(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipe.to(_SCREAMING_SNAKE_CASE ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipe(**self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = output.images _UpperCAmelCase = pipe( **self.get_dummy_inputs(_SCREAMING_SNAKE_CASE ) , return_dict=_SCREAMING_SNAKE_CASE , )[0] _UpperCAmelCase = image[0, -3:, -3:, -1] _UpperCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) _UpperCAmelCase = np.array( [0.6959826, 0.868279, 0.7558092, 0.68769467, 0.85805804, 0.65977496, 0.44885302, 0.5959111, 0.4251595] ) 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 ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy' ) _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/hint_image_cat.png' ) _UpperCAmelCase = torch.from_numpy(np.array(_SCREAMING_SNAKE_CASE ) ).float() / 255.0 _UpperCAmelCase = hint.permute(2 , 0 , 1 ).unsqueeze(0 ) _UpperCAmelCase = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = KandinskyVaaControlnetPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-controlnet-depth' , torch_dtype=torch.floataa ) _UpperCAmelCase = pipeline.to(_SCREAMING_SNAKE_CASE ) pipeline.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 'A robot, 4k photo' _UpperCAmelCase = torch.Generator(device='cuda' ).manual_seed(0 ) _UpperCAmelCase , _UpperCAmelCase = pipe_prior( _SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=5 , negative_prompt='' , ).to_tuple() _UpperCAmelCase = torch.Generator(device='cuda' ).manual_seed(0 ) _UpperCAmelCase = pipeline( image_embeds=_SCREAMING_SNAKE_CASE , negative_image_embeds=_SCREAMING_SNAKE_CASE , hint=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=100 , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
329
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
1
import requests from bsa import BeautifulSoup def lowerCAmelCase__ ( a__: str = "AAPL" ) -> str: '''simple docstring''' _UpperCAmelCase = F'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' _UpperCAmelCase = BeautifulSoup(requests.get(a__ ).text , 'html.parser' ) _UpperCAmelCase = 'My(6px) Pos(r) smartphone_Mt(6px)' return soup.find('div' , class_=class_ ).find('span' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
329
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
1
import itertools import math def lowerCAmelCase__ ( a__: int ) -> bool: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def lowerCAmelCase__ ( ) -> int: '''simple docstring''' _UpperCAmelCase = 2 while True: if is_prime(a__ ): yield num num += 1 def lowerCAmelCase__ ( a__: int = 1_0_0_0_1 ) -> int: '''simple docstring''' return next(itertools.islice(prime_generator() , nth - 1 , a__ ) ) if __name__ == "__main__": print(f'''{solution() = }''')
329
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _UpperCAmelCase = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE , os.listdir(_SCREAMING_SNAKE_CASE )[0] , 'snapshots' ) )] _UpperCAmelCase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 4 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1514745 ) < 1e-3 assert np.abs(np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 49947.875 ) < 5e-1 _UpperCAmelCase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_SCREAMING_SNAKE_CASE ) == num_samples def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05652401) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2383808.2) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = FlaxDDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = scheduler.create_state() _UpperCAmelCase = scheduler_state _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045043945) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2347693.5) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = jax.random.split(jax.random.PRNGKey(0 ) , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # With memory efficient attention _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , use_memory_efficient_attention=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
329
1
lowerCAmelCase__ :Optional[Any] = '''Input must be a string of 8 numbers plus letter''' lowerCAmelCase__ :List[Any] = '''TRWAGMYFPDXBNJZSQVHLCKE''' def lowerCAmelCase__ ( a__: str ) -> bool: '''simple docstring''' if not isinstance(a__ , a__ ): _UpperCAmelCase = F'''Expected string as input, found {type(a__ ).__name__}''' raise TypeError(a__ ) _UpperCAmelCase = spanish_id.replace('-' , '' ).upper() if len(a__ ) != 9: raise ValueError(a__ ) try: _UpperCAmelCase = int(spanish_id_clean[0:8] ) _UpperCAmelCase = spanish_id_clean[8] except ValueError as ex: raise ValueError(a__ ) from ex if letter.isdigit(): raise ValueError(a__ ) return letter == LOOKUP_LETTERS[number % 2_3] if __name__ == "__main__": import doctest doctest.testmod()
329
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(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ :int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} if prompt is not None: _UpperCAmelCase = prompt if generate_kwargs is not None: _UpperCAmelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _UpperCAmelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,' ' please use only one' ) _UpperCAmelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. ''' 'Note also that one single text can be provided for conditional image to text generation.' ) _UpperCAmelCase = self.model.config.model_type if model_type == "git": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids _UpperCAmelCase = [self.tokenizer.cls_token_id] + input_ids _UpperCAmelCase = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _UpperCAmelCase = None return model_inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs['input_ids'] ) ): _UpperCAmelCase = None if generate_kwargs is None: _UpperCAmelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _UpperCAmelCase = model_inputs.pop(self.model.main_input_name ) _UpperCAmelCase = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = [] for output_ids in model_outputs: _UpperCAmelCase = { 'generated_text': self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
329
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast @require_vision class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = BlipImageProcessor() _UpperCAmelCase = BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel' ) _UpperCAmelCase = BlipProcessor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ).tokenizer def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ).image_processor def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCAmelCase = [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = BlipProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) _UpperCAmelCase = self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) _UpperCAmelCase = BlipProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _SCREAMING_SNAKE_CASE ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BlipProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='np' ) _UpperCAmelCase = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BlipProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 'lower newer' _UpperCAmelCase = processor(text=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tokenizer(_SCREAMING_SNAKE_CASE , return_token_type_ids=_SCREAMING_SNAKE_CASE ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BlipProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 'lower newer' _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] ) # test if it raises when no input is passed with pytest.raises(_SCREAMING_SNAKE_CASE ): processor() def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BlipProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _UpperCAmelCase = processor.batch_decode(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = tokenizer.batch_decode(_SCREAMING_SNAKE_CASE ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = self.get_tokenizer() _UpperCAmelCase = BlipProcessor(tokenizer=_SCREAMING_SNAKE_CASE , image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 'lower newer' _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = processor(text=_SCREAMING_SNAKE_CASE , images=_SCREAMING_SNAKE_CASE ) # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask'] self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'input_ids', 'attention_mask'] )
329
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
1
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup lowerCAmelCase__ :Union[str, Any] = { '''User-Agent''': '''Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36''' ''' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582''' } def lowerCAmelCase__ ( a__: str = "dhaka" , a__: int = 5 ) -> int: '''simple docstring''' _UpperCAmelCase = min(a__ , 5_0 ) # Prevent abuse! _UpperCAmelCase = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } _UpperCAmelCase = requests.get('https://www.google.com/search' , params=a__ , headers=a__ ) _UpperCAmelCase = BeautifulSoup(html.text , 'html.parser' ) _UpperCAmelCase = ''.join( re.findall(R'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) _UpperCAmelCase = json.dumps(a__ ) _UpperCAmelCase = json.loads(a__ ) _UpperCAmelCase = re.findall( R'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , a__ , ) if not matched_google_image_data: return 0 _UpperCAmelCase = re.sub( R'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(a__ ) , ) _UpperCAmelCase = re.findall( R'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , a__ , ) for index, fixed_full_res_image in enumerate(a__ ): if index >= max_images: return index _UpperCAmelCase = bytes(a__ , 'ascii' ).decode( 'unicode-escape' ) _UpperCAmelCase = bytes(a__ , 'ascii' ).decode( 'unicode-escape' ) _UpperCAmelCase = urllib.request.build_opener() _UpperCAmelCase = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(a__ ) _UpperCAmelCase = F'''query_{query.replace(" " , "_" )}''' if not os.path.exists(a__ ): os.makedirs(a__ ) urllib.request.urlretrieve( # noqa: S310 a__ , F'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: lowerCAmelCase__ :List[str] = download_images_from_google_query(sys.argv[1]) print(f'''{image_count} images were downloaded to disk.''') except IndexError: print('''Please provide a search term.''') raise
329
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
1
import unittest import numpy as np from datasets import load_dataset 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 BeitImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=False , ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = size if size is not None else {'height': 20, 'width': 20} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 18, 'width': 18} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_center_crop _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_reduce_labels def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def lowerCAmelCase__ ( ) -> List[str]: '''simple docstring''' _UpperCAmelCase = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) _UpperCAmelCase = Image.open(dataset[0]['file'] ) _UpperCAmelCase = Image.open(dataset[1]['file'] ) return image, map def lowerCAmelCase__ ( ) -> Dict: '''simple docstring''' _UpperCAmelCase = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) _UpperCAmelCase = Image.open(ds[0]['file'] ) _UpperCAmelCase = Image.open(ds[1]['file'] ) _UpperCAmelCase = Image.open(ds[2]['file'] ) _UpperCAmelCase = Image.open(ds[3]['file'] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = BeitImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = BeitImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = 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 , 'do_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 20, 'width': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) self.assertEqual(image_processor.do_reduce_labels , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_SCREAMING_SNAKE_CASE , torchify=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [] for image in image_inputs: self.assertIsInstance(_SCREAMING_SNAKE_CASE , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input _UpperCAmelCase = image_processing(image_inputs[0] , maps[0] , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test not batched input (PIL images) _UpperCAmelCase , _UpperCAmelCase = prepare_semantic_single_inputs() _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 1, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) # Test batched input (PIL images) _UpperCAmelCase , _UpperCAmelCase = prepare_semantic_batch_inputs() _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertEqual( encoding['pixel_values'].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual( encoding['labels'].shape , ( 2, self.image_processor_tester.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) self.assertEqual(encoding['labels'].dtype , torch.long ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 _UpperCAmelCase , _UpperCAmelCase = prepare_semantic_single_inputs() _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 150 ) _UpperCAmelCase = True _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertTrue(encoding['labels'].min().item() >= 0 ) self.assertTrue(encoding['labels'].max().item() <= 255 )
329
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = AutoConfig.from_pretrained(a__ ) _UpperCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=a__ ) _UpperCAmelCase = checkpoints.load_tax_checkpoint(a__ ) _UpperCAmelCase = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": _UpperCAmelCase = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": _UpperCAmelCase = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['encoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_global_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = tax_mlp_layer_norm _UpperCAmelCase = flax_model_encoder_layer_block # Only for layer 0: _UpperCAmelCase = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_global_rel_embedding # Assigning _UpperCAmelCase = tax_model['target']['encoder']['encoder_norm']['scale'] _UpperCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] _UpperCAmelCase = tax_enc_dec_attention_module['key']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['out']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['query']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['decoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_pre_attention_layer_norm _UpperCAmelCase = tax_enc_dec_attention_key _UpperCAmelCase = tax_enc_dec_attention_out _UpperCAmelCase = tax_enc_dec_attention_query _UpperCAmelCase = tax_enc_dec_attention_value _UpperCAmelCase = tax_cross_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = txa_mlp_layer_norm _UpperCAmelCase = flax_model_decoder_layer_block # Decoder Normalization _UpperCAmelCase = tax_model['target']['decoder']['decoder_norm']['scale'] _UpperCAmelCase = txa_decoder_norm # Only for layer 0: _UpperCAmelCase = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_decoder_rel_embedding # Token Embeddings _UpperCAmelCase = tax_model['target']['token_embedder']['embedding'] _UpperCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: _UpperCAmelCase = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(a__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path the T5X checkpoint.''' ) parser.add_argument('''--config_name''', default=None, type=str, required=True, help='''Config name of LongT5/T5 model.''') parser.add_argument( '''--flax_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output FLAX model.''' ) lowerCAmelCase__ :List[str] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
329
1
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , ) -> List[Any]: """simple docstring""" _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 18} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866443634033203, 0.6618829369544983, 0.3891746401786804], [-0.6042559146881104, -0.02295008860528469, 0.5423797369003296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Tuple = ImageGPTImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = ImageGPTImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'clusters' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 18} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) _UpperCAmelCase = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(_SCREAMING_SNAKE_CASE , obj[key] ) ) else: self.assertEqual(obj[key] , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(_SCREAMING_SNAKE_CASE , 'image_processor.json' ) image_processor_first.to_json_file(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_json_file(_SCREAMING_SNAKE_CASE ).to_dict() _UpperCAmelCase = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_SCREAMING_SNAKE_CASE , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_pretrained(_SCREAMING_SNAKE_CASE ).to_dict() _UpperCAmelCase = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(_SCREAMING_SNAKE_CASE , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , _SCREAMING_SNAKE_CASE ) @unittest.skip('ImageGPT requires clusters at initialization' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def lowerCAmelCase__ ( ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = load_dataset('hf-internal-testing/fixtures_image_utils' , split='test' ) _UpperCAmelCase = Image.open(dataset[4]['file'] ) _UpperCAmelCase = Image.open(dataset[5]['file'] ) _UpperCAmelCase = [imagea, imagea] return images @require_vision @require_torch class __a ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = ImageGPTImageProcessor.from_pretrained('openai/imagegpt-small' ) _UpperCAmelCase = prepare_images() # test non-batched _UpperCAmelCase = image_processing(images[0] , return_tensors='pt' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) _UpperCAmelCase = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , _SCREAMING_SNAKE_CASE ) # test batched _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) _UpperCAmelCase = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , _SCREAMING_SNAKE_CASE )
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : str = 'ctrl' _a : Tuple = ['past_key_values'] _a : List[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=246534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import datasets lowerCAmelCase__ :int = '''\ @InProceedings{conneau2018xnli, author = "Conneau, Alexis and Rinott, Ruty and Lample, Guillaume and Williams, Adina and Bowman, Samuel R. and Schwenk, Holger and Stoyanov, Veselin", title = "XNLI: Evaluating Cross-lingual Sentence Representations", booktitle = "Proceedings of the 2018 Conference on Empirical Methods in Natural Language Processing", year = "2018", publisher = "Association for Computational Linguistics", location = "Brussels, Belgium", } ''' lowerCAmelCase__ :Union[str, Any] = '''\ XNLI is a subset of a few thousand examples from MNLI which has been translated into a 14 different languages (some low-ish resource). As with MNLI, the goal is to predict textual entailment (does sentence A imply/contradict/neither sentence B) and is a classification task (given two sentences, predict one of three labels). ''' lowerCAmelCase__ :Optional[Any] = ''' Computes XNLI score which is just simple accuracy. Args: predictions: Predicted labels. references: Ground truth labels. Returns: \'accuracy\': accuracy Examples: >>> predictions = [0, 1] >>> references = [0, 1] >>> xnli_metric = datasets.load_metric("xnli") >>> results = xnli_metric.compute(predictions=predictions, references=references) >>> print(results) {\'accuracy\': 1.0} ''' def lowerCAmelCase__ ( a__: str , a__: Dict ) -> Any: '''simple docstring''' return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __a ( datasets.Metric ): def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32' ), 'references': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32' ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return {"accuracy": simple_accuracy(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )}
329
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> Dict: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : str = DeformableDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DeformableDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = 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 , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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, ) , ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = DeformableDetrImageProcessor() _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = DeformableDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
329
1
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): lowerCAmelCase__ :Optional[int] = yaml.safe_load( '''\ name: "" allow_empty: false allow_empty_text: true subsections: - name: "Dataset Card for X" # First-level markdown heading allow_empty: false allow_empty_text: true subsections: - name: "Table of Contents" allow_empty: false allow_empty_text: false subsections: null - name: "Dataset Description" allow_empty: false allow_empty_text: false subsections: - name: "Dataset Summary" allow_empty: false allow_empty_text: false subsections: null - name: "Supported Tasks and Leaderboards" allow_empty: true allow_empty_text: true subsections: null - name: Languages allow_empty: false allow_empty_text: true subsections: null ''' ) lowerCAmelCase__ :Optional[int] = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } lowerCAmelCase__ :int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :str = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. #### Extra Ignored Subsection ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :Tuple = { '''name''': '''root''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ { '''name''': '''Dataset Card for My Dataset''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [ {'''name''': '''Table of Contents''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': []}, { '''name''': '''Dataset Description''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Dataset Summary''', '''text''': '''Some text here.''', '''is_empty_text''': False, '''subsections''': [ { '''name''': '''Extra Ignored Subsection''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], } ], }, { '''name''': '''Supported Tasks and Leaderboards''', '''text''': '''''', '''is_empty_text''': True, '''subsections''': [], }, {'''name''': '''Languages''', '''text''': '''Language Text''', '''is_empty_text''': False, '''subsections''': []}, ], }, ], } ], } lowerCAmelCase__ :int = '''\ --- --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :List[Any] = ( '''The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.''' ) lowerCAmelCase__ :Optional[Any] = '''\ # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :Optional[Any] = ( '''The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.''' ) lowerCAmelCase__ :int = '''\ --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :int = '''The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.''' lowerCAmelCase__ :List[str] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :Union[str, Any] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).''' lowerCAmelCase__ :List[str] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ''' lowerCAmelCase__ :Dict = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.''' lowerCAmelCase__ :Optional[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Languages Language Text ''' lowerCAmelCase__ :Optional[int] = '''The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.''' lowerCAmelCase__ :Optional[int] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages ''' lowerCAmelCase__ :List[str] = '''The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.''' lowerCAmelCase__ :Union[str, Any] = '''\ --- language: - zh - en --- ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :Any = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.''' lowerCAmelCase__ :List[Any] = '''\ --- language: - zh - en --- # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text # Dataset Card My Dataset ''' lowerCAmelCase__ :Any = '''The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.''' lowerCAmelCase__ :str = '''\ --- language: - zh - en --- # Dataset Card My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :List[Any] = '''The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.''' lowerCAmelCase__ :Any = '''''' lowerCAmelCase__ :Any = '''The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.''' lowerCAmelCase__ :int = '''\ --- language: - zh - en --- # Dataset Card for My Dataset # Dataset Card for My Dataset ## Table of Contents Some text here. ## Dataset Description Some text here. ### Dataset Summary Some text here. ### Supported Tasks and Leaderboards ### Languages Language Text ''' lowerCAmelCase__ :Optional[Any] = '''The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.''' @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCAmelCase__ ( a__: Union[str, Any] , a__: Optional[int] ) -> List[str]: '''simple docstring''' assert ReadMe.from_string(a__ , a__ ).to_dict() == expected_dict @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCAmelCase__ ( a__: Optional[Any] , a__: List[str] ) -> Dict: '''simple docstring''' with pytest.raises(a__ , match=re.escape(expected_error.format(path='root' ) ) ): _UpperCAmelCase = ReadMe.from_string(a__ , a__ ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCAmelCase__ ( a__: Optional[int] , a__: Tuple ) -> List[str]: '''simple docstring''' with pytest.raises(a__ , match=re.escape(expected_error.format(path='root' ) ) ): ReadMe.from_string(a__ , a__ ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCAmelCase__ ( a__: List[str] ) -> Union[str, Any]: '''simple docstring''' ReadMe.from_string(a__ , a__ , suppress_parsing_errors=a__ ) @pytest.mark.parametrize( 'readme_md, expected_dict' , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCAmelCase__ ( a__: Union[str, Any] , a__: Tuple ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = Path(a__ ) / 'README.md' with open(a__ , 'w+' ) as readme_file: readme_file.write(a__ ) _UpperCAmelCase = ReadMe.from_readme(a__ , a__ ).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCAmelCase__ ( a__: str , a__: int ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = Path(a__ ) / 'README.md' with open(a__ , 'w+' ) as readme_file: readme_file.write(a__ ) _UpperCAmelCase = expected_error.format(path=a__ ) with pytest.raises(a__ , match=re.escape(a__ ) ): _UpperCAmelCase = ReadMe.from_readme(a__ , a__ ) readme.validate() @pytest.mark.parametrize( 'readme_md, expected_error' , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCAmelCase__ ( a__: str , a__: int ) -> Any: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = Path(a__ ) / 'README.md' with open(a__ , 'w+' ) as readme_file: readme_file.write(a__ ) _UpperCAmelCase = expected_error.format(path=a__ ) with pytest.raises(a__ , match=re.escape(a__ ) ): ReadMe.from_readme(a__ , a__ ) @pytest.mark.parametrize( 'readme_md,' , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCAmelCase__ ( a__: str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmp_dir: _UpperCAmelCase = Path(a__ ) / 'README.md' with open(a__ , 'w+' ) as readme_file: readme_file.write(a__ ) ReadMe.from_readme(a__ , a__ , suppress_parsing_errors=a__ )
329
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a ( unittest.TestCase ): _a : List[str] = JukeboxTokenizer _a : List[Any] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
329
1
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowerCAmelCase__ :int = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowerCAmelCase__ :Tuple = [file for file in filepaths if file != file.lower()] if upper_files: print(f'''{len(upper_files)} files contain uppercase characters:''') print('''\n'''.join(upper_files) + '''\n''') lowerCAmelCase__ :List[Any] = [file for file in filepaths if ''' ''' in file] if space_files: print(f'''{len(space_files)} files contain space characters:''') print('''\n'''.join(space_files) + '''\n''') lowerCAmelCase__ :Optional[Any] = [file for file in filepaths if '''-''' in file] if hyphen_files: print(f'''{len(hyphen_files)} files contain hyphen characters:''') print('''\n'''.join(hyphen_files) + '''\n''') lowerCAmelCase__ :Tuple = [file for file in filepaths if os.sep not in file] if nodir_files: print(f'''{len(nodir_files)} files are not in a directory:''') print('''\n'''.join(nodir_files) + '''\n''') lowerCAmelCase__ :List[str] = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
329
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ :Optional[int] = logging.getLogger(__name__) def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = argparse.ArgumentParser( description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.' ) parser.add_argument( '--dataset_name' , type=a__ , default='wikitext' , help='Name of the training. Explore datasets at: hf.co/datasets.' , ) parser.add_argument( '--dataset_config' , type=a__ , default='wikitext-103-raw-v1' , help='Configuration name of the dataset.' ) parser.add_argument( '--tokenizer_name_or_path' , type=a__ , default='sayakpaul/unigram-tokenizer-wikitext' , help='Tokenizer identifier. Can be a local filepath or a Hub identifier.' , ) parser.add_argument( '--shard_size' , type=a__ , default=1_0_0_0 , help='Number of entries to go in a single shard.' , ) parser.add_argument('--split' , type=a__ , default='train' , choices=['train', 'test', 'validation'] ) parser.add_argument( '--limit' , default=a__ , type=a__ , help='Limit the number of shards (used for debugging).' , ) parser.add_argument( '--max_length' , type=a__ , default=5_1_2 , help='Maximum sequence length. For training on TPUs, it helps to have a maximum' ' sequence length that is a multiple of 8.' , ) parser.add_argument( '--output_dir' , default='tf-tpu' , type=a__ , help='Output directory where the TFRecord shards will be saved. If the' ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord' ' shards will be directly saved to a Google Cloud Storage bucket.' , ) _UpperCAmelCase = parser.parse_args() return args def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[Any]: '''simple docstring''' def fn(a__: str ): return tokenizer(examples['text'] ) return fn def lowerCAmelCase__ ( a__: List[str] ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for i in range(len(tokenized_data['input_ids'] ) ): _UpperCAmelCase = { 'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i] ) ), 'attention_mask': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i] ) ), } _UpperCAmelCase = tf.train.Features(feature=a__ ) _UpperCAmelCase = tf.train.Example(features=a__ ) _UpperCAmelCase = example.SerializeToString() records.append(a__ ) return records def lowerCAmelCase__ ( a__: Union[str, Any] ) -> int: '''simple docstring''' _UpperCAmelCase = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: _UpperCAmelCase = min(len(a__ ) , args.limit ) _UpperCAmelCase = dataset.select(range(a__ ) ) print(F'''Limiting the dataset to {args.limit} entries.''' ) _UpperCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _UpperCAmelCase = os.path.join(args.output_dir , args.split ) if not os.path.exists(a__ ): os.makedirs(a__ ) else: _UpperCAmelCase = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. _UpperCAmelCase = tokenize_function(a__ ) _UpperCAmelCase = dataset.map(a__ , batched=a__ , num_proc=4 , remove_columns=['text'] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(a__: Optional[int] ): # Concatenate all texts. _UpperCAmelCase = {k: sum(examples[k] , [] ) for k in examples.keys()} _UpperCAmelCase = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _UpperCAmelCase = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _UpperCAmelCase = { k: [t[i : i + args.max_length] for i in range(0 , a__ , args.max_length )] for k, t in concatenated_examples.items() } return result _UpperCAmelCase = dataset_tokenized.map(a__ , batched=a__ , batch_size=1_0_0_0 , num_proc=4 ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 for shard in range(0 , len(a__ ) , args.shard_size ): _UpperCAmelCase = grouped_dataset[shard : shard + args.shard_size] _UpperCAmelCase = len(dataset_snapshot['input_ids'] ) _UpperCAmelCase = os.path.join(a__ , F'''dataset-{shard_count}-{records_containing}.tfrecord''' ) _UpperCAmelCase = get_serialized_examples(a__ ) with tf.io.TFRecordWriter(a__ ) as out_file: for i in range(len(a__ ) ): _UpperCAmelCase = serialized_examples[i] out_file.write(a__ ) print('Wrote file {} containing {} records'.format(a__ , a__ ) ) shard_count += 1 total_records += records_containing with open(F'''split-{args.split}-records-count.txt''' , 'w' ) as f: print(F'''Total {args.split} records: {total_records}''' , file=a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = parse_args() main(args)
329
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , ) -> int: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 20} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 18, 'width': 18} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_center_crop _UpperCAmelCase = crop_size _UpperCAmelCase = do_flip_channel_order def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = MobileViTImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MobileViTImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = 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 , 'do_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_flip_channel_order' ) ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 20} ) self.assertEqual(image_processor.crop_size , {'height': 18, 'width': 18} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any]=1_0 ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for _ in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCAmelCase__ ( a__: List[str] , a__: Any=1_0 ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [] for step in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(a__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , a__ ) _UpperCAmelCase = torch.load(a__ ) scheduler.load_state_dict(a__ ) return lrs @require_torch class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-3_0, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_SCREAMING_SNAKE_CASE , weight_decay=0.0 , relative_step=_SCREAMING_SNAKE_CASE , scale_parameter=_SCREAMING_SNAKE_CASE , warmup_init=_SCREAMING_SNAKE_CASE , ) for _ in range(1000 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __a ( unittest.TestCase ): _a : Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _a : Dict = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _a : List[Any] = 10 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE , msg=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListAlmostEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tol=1e-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_SCREAMING_SNAKE_CASE ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , msg=f'''failed for {scheduler_func} in save and reload''' ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = fn def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
329
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : str = 'ctrl' _a : Tuple = ['past_key_values'] _a : List[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=246534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
329
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Any = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any] , a__: Dict , a__: Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = original_name.split('.' )[0] _UpperCAmelCase = key.split('.' ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 2] ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 1] ) _UpperCAmelCase = orig_block_num - offset _UpperCAmelCase = key.replace(F'''{orig_block_num}.{layer_num}.{original_name}''' , F'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def lowerCAmelCase__ ( a__: Tuple ) -> int: '''simple docstring''' _UpperCAmelCase = OrderedDict() _UpperCAmelCase , _UpperCAmelCase = 0, 0 for key, value in state_dict.items(): if key.startswith('network' ): _UpperCAmelCase = key.replace('network' , 'poolformer.encoder' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('bias' ) and "patch_embed" not in key: patch_emb_offset += 1 _UpperCAmelCase = key[: key.find('proj' )] _UpperCAmelCase = key.replace(a__ , F'''patch_embeddings.{total_embed_found}.''' ) _UpperCAmelCase = key.replace('proj' , 'projection' ) if key.endswith('bias' ): total_embed_found += 1 if "patch_embeddings" in key: _UpperCAmelCase = 'poolformer.encoder.' + key if "mlp.fc1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc1' , 'output.conv1' ) if "mlp.fc2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc2' , 'output.conv2' ) if "norm1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm1' , 'before_norm' ) if "norm2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm2' , 'after_norm' ) if "layer_scale_1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_1' , 'layer_scale_1' ) if "layer_scale_2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_2' , 'layer_scale_2' ) if "head" in key: _UpperCAmelCase = key.replace('head' , 'classifier' ) _UpperCAmelCase = value return new_state_dict def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return image @torch.no_grad() def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: Any ) -> Dict: '''simple docstring''' _UpperCAmelCase = PoolFormerConfig() # set attributes based on model_name _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = model_name[-3:] _UpperCAmelCase = 1_0_0_0 _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = (1, 1_0_0_0) # set config attributes _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} if size == "s12": _UpperCAmelCase = [2, 2, 6, 2] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s24": _UpperCAmelCase = [4, 4, 1_2, 4] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.9 elif size == "m36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 elif size == "m48": _UpperCAmelCase = [8, 8, 2_4, 8] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 else: raise ValueError(F'''Size {size} not supported''' ) # load image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) # Prepare image _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) # rename keys _UpperCAmelCase = rename_keys(a__ ) # create HuggingFace model and load state dict _UpperCAmelCase = PoolFormerForImageClassification(a__ ) model.load_state_dict(a__ ) model.eval() # Define image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values # forward pass _UpperCAmelCase = model(a__ ) _UpperCAmelCase = outputs.logits # define expected logit slices for different models if size == "s12": _UpperCAmelCase = torch.tensor([-0.3_045, -0.6_758, -0.4_869] ) elif size == "s24": _UpperCAmelCase = torch.tensor([0.4_402, -0.1_374, -0.8_045] ) elif size == "s36": _UpperCAmelCase = torch.tensor([-0.6_080, -0.5_133, -0.5_898] ) elif size == "m36": _UpperCAmelCase = torch.tensor([0.3_952, 0.2_263, -1.2_668] ) elif size == "m48": _UpperCAmelCase = torch.tensor([0.1_167, -0.0_656, -0.3_423] ) else: raise ValueError(F'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , a__ , atol=1e-2 ) # finally, save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(a__ ).mkdir(exist_ok=a__ ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
329
1
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase__ :Tuple = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: List[str] , a__: List[str] ) -> int: '''simple docstring''' _UpperCAmelCase = b.T _UpperCAmelCase = np.sum(np.square(a__ ) , axis=1 ) _UpperCAmelCase = np.sum(np.square(a__ ) , axis=0 ) _UpperCAmelCase = np.matmul(a__ , a__ ) _UpperCAmelCase = aa[:, None] - 2 * ab + ba[None, :] return d def lowerCAmelCase__ ( a__: List[Any] , a__: str ) -> Dict: '''simple docstring''' _UpperCAmelCase = x.reshape(-1 , 3 ) _UpperCAmelCase = squared_euclidean_distance(a__ , a__ ) return np.argmin(a__ , axis=1 ) class __a ( UpperCAmelCase ): _a : Optional[Any] = ['pixel_values'] def __init__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = size if size is not None else {'height': 256, 'width': 256} _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = np.array(_SCREAMING_SNAKE_CASE ) if clusters is not None else None _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = resample _UpperCAmelCase = do_normalize _UpperCAmelCase = do_color_quantize def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( _SCREAMING_SNAKE_CASE , size=(size['height'], size['width']) , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = rescale(image=_SCREAMING_SNAKE_CASE , scale=1 / 127.5 , data_format=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = image - 1 return image def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image: """simple docstring""" _UpperCAmelCase = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase = size if size is not None else self.size _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = resample if resample is not None else self.resample _UpperCAmelCase = do_normalize if do_normalize is not None else self.do_normalize _UpperCAmelCase = do_color_quantize if do_color_quantize is not None else self.do_color_quantize _UpperCAmelCase = clusters if clusters is not None else self.clusters _UpperCAmelCase = np.array(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. _UpperCAmelCase = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: _UpperCAmelCase = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_normalize: _UpperCAmelCase = [self.normalize(image=_SCREAMING_SNAKE_CASE ) for image in images] if do_color_quantize: _UpperCAmelCase = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) _UpperCAmelCase = np.array(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = color_quantize(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) _UpperCAmelCase = images.shape[0] _UpperCAmelCase = images.reshape(_SCREAMING_SNAKE_CASE , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] _UpperCAmelCase = {'input_ids': images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE )
329
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = process _UpperCAmelCase = params def __len__( self ) -> Union[str, Any]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = self.dataset[i] _UpperCAmelCase = self.process(_SCREAMING_SNAKE_CASE , **self.params ) return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = loader _UpperCAmelCase = infer _UpperCAmelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether _UpperCAmelCase = None _UpperCAmelCase = loader_batch_size # Internal bookkeeping _UpperCAmelCase = None _UpperCAmelCase = None def __len__( self ) -> Any: """simple docstring""" return len(self.loader ) def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice _UpperCAmelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) _UpperCAmelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Convert ModelOutput to tuple first _UpperCAmelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around _UpperCAmelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. _UpperCAmelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 _UpperCAmelCase = self._loader_batch_data.__class__(_SCREAMING_SNAKE_CASE ) self._loader_batch_index += 1 return result def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch _UpperCAmelCase = next(self.iterator ) _UpperCAmelCase = self.infer(_SCREAMING_SNAKE_CASE , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size # Setting internal index to unwrap the batch _UpperCAmelCase = processed _UpperCAmelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __iter__( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) _UpperCAmelCase = None return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if self.subiterator is None: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item _UpperCAmelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) _UpperCAmelCase = next(self.subiterator ) return processed class __a ( UpperCAmelCase ): def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = False _UpperCAmelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator while not is_last: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size _UpperCAmelCase = processed _UpperCAmelCase = 0 while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator else: _UpperCAmelCase = processed _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) return accumulator class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = key def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return self.dataset[i][self.key] class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = keya _UpperCAmelCase = keya def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
329
1
import asyncio import os import shutil import subprocess import sys import tempfile import unittest from distutils.util import strtobool from functools import partial from pathlib import Path from typing import List, Union from unittest import mock import torch from ..state import AcceleratorState, PartialState from ..utils import ( gather, is_bnb_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_mps_available, is_safetensors_available, is_tensorboard_available, is_torch_version, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) def lowerCAmelCase__ ( a__: Dict , a__: Tuple=False ) -> Any: '''simple docstring''' try: _UpperCAmelCase = os.environ[key] except KeyError: # KEY isn't set, default to `default`. _UpperCAmelCase = default else: # KEY is set, convert it to True or False. try: _UpperCAmelCase = strtobool(a__ ) except ValueError: # More values are supported, but let's keep the message simple. raise ValueError(F'''If set, {key} must be yes or no.''' ) return _value lowerCAmelCase__ :Tuple = parse_flag_from_env('''RUN_SLOW''', default=False) def lowerCAmelCase__ ( a__: Optional[Any] ) -> int: '''simple docstring''' return unittest.skip('Test was skipped' )(a__ ) def lowerCAmelCase__ ( a__: Dict ) -> Any: '''simple docstring''' return unittest.skipUnless(_run_slow_tests , 'test is slow' )(a__ ) def lowerCAmelCase__ ( a__: Tuple ) -> Optional[Any]: '''simple docstring''' return unittest.skipUnless(not torch.cuda.is_available() , 'test requires only a CPU' )(a__ ) def lowerCAmelCase__ ( a__: Dict ) -> int: '''simple docstring''' return unittest.skipUnless(torch.cuda.is_available() , 'test requires a GPU' )(a__ ) def lowerCAmelCase__ ( a__: Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return unittest.skipUnless(is_xpu_available() , 'test requires a XPU' )(a__ ) def lowerCAmelCase__ ( a__: Any ) -> Dict: '''simple docstring''' return unittest.skipUnless(is_mps_available() , 'test requires a `mps` backend support in `torch`' )(a__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> Any: '''simple docstring''' return unittest.skipUnless( is_transformers_available() and is_datasets_available() , 'test requires the Hugging Face suite' )(a__ ) def lowerCAmelCase__ ( a__: Tuple ) -> List[str]: '''simple docstring''' return unittest.skipUnless(is_bnb_available() , 'test requires the bitsandbytes library' )(a__ ) def lowerCAmelCase__ ( a__: str ) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_tpu_available() , 'test requires TPU' )(a__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() == 1 , 'test requires a GPU' )(a__ ) def lowerCAmelCase__ ( a__: str ) -> List[str]: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() == 1 , 'test requires a XPU' )(a__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> Optional[Any]: '''simple docstring''' return unittest.skipUnless(torch.cuda.device_count() > 1 , 'test requires multiple GPUs' )(a__ ) def lowerCAmelCase__ ( a__: str ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(torch.xpu.device_count() > 1 , 'test requires multiple XPUs' )(a__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> Tuple: '''simple docstring''' return unittest.skipUnless(is_safetensors_available() , 'test requires safetensors' )(a__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> int: '''simple docstring''' return unittest.skipUnless(is_deepspeed_available() , 'test requires DeepSpeed' )(a__ ) def lowerCAmelCase__ ( a__: List[str] ) -> List[Any]: '''simple docstring''' return unittest.skipUnless(is_torch_version('>=' , '1.12.0' ) , 'test requires torch version >= 1.12.0' )(a__ ) def lowerCAmelCase__ ( a__: Union[str, Any]=None , a__: Tuple=None ) -> str: '''simple docstring''' if test_case is None: return partial(a__ , version=a__ ) return unittest.skipUnless(is_torch_version('>=' , a__ ) , F'''test requires torch version >= {version}''' )(a__ ) def lowerCAmelCase__ ( a__: int ) -> Optional[Any]: '''simple docstring''' return unittest.skipUnless(is_tensorboard_available() , 'test requires Tensorboard' )(a__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> Any: '''simple docstring''' return unittest.skipUnless(is_wandb_available() , 'test requires wandb' )(a__ ) def lowerCAmelCase__ ( a__: Optional[Any] ) -> str: '''simple docstring''' return unittest.skipUnless(is_comet_ml_available() , 'test requires comet_ml' )(a__ ) lowerCAmelCase__ :Optional[int] = ( any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() ) def lowerCAmelCase__ ( a__: Any ) -> Optional[Any]: '''simple docstring''' return unittest.skipUnless( _atleast_one_tracker_available , 'test requires at least one tracker to be available and for `comet_ml` to not be installed' , )(a__ ) class __a ( unittest.TestCase ): _a : Optional[int] = True @classmethod def UpperCAmelCase__ ( cls ) -> int: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() @classmethod def UpperCAmelCase__ ( cls ) -> Any: """simple docstring""" if os.path.exists(cls.tmpdir ): shutil.rmtree(cls.tmpdir ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" if self.clear_on_setup: for path in Path(self.tmpdir ).glob('**/*' ): if path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(_SCREAMING_SNAKE_CASE ) class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" super().tearDown() # Reset the state of the AcceleratorState singleton. AcceleratorState._reset_state() PartialState._reset_state() class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _UpperCAmelCase = mocks if isinstance(_SCREAMING_SNAKE_CASE , (tuple, list) ) else [mocks] for m in self.mocks: m.start() self.addCleanup(m.stop ) def lowerCAmelCase__ ( a__: Tuple ) -> str: '''simple docstring''' _UpperCAmelCase = AcceleratorState() _UpperCAmelCase = tensor[None].clone().to(state.device ) _UpperCAmelCase = gather(a__ ).cpu() _UpperCAmelCase = tensor[0].cpu() for i in range(tensors.shape[0] ): if not torch.equal(tensors[i] , a__ ): return False return True class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _UpperCAmelCase = returncode _UpperCAmelCase = stdout _UpperCAmelCase = stderr async def lowerCAmelCase__ ( a__: str , a__: Any ) -> Dict: '''simple docstring''' while True: _UpperCAmelCase = await stream.readline() if line: callback(a__ ) else: break async def lowerCAmelCase__ ( a__: Optional[int] , a__: List[str]=None , a__: Dict=None , a__: List[str]=None , a__: str=False , a__: Optional[Any]=False ) -> _RunOutput: '''simple docstring''' if echo: print('\nRunning: ' , ' '.join(a__ ) ) _UpperCAmelCase = await asyncio.create_subprocess_exec( cmd[0] , *cmd[1:] , stdin=a__ , stdout=asyncio.subprocess.PIPE , stderr=asyncio.subprocess.PIPE , env=a__ , ) # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait # # If it starts hanging, will need to switch to the following code. The problem is that no data # will be seen until it's done and if it hangs for example there will be no debug info. # out, err = await p.communicate() # return _RunOutput(p.returncode, out, err) _UpperCAmelCase = [] _UpperCAmelCase = [] def tee(a__: int , a__: List[str] , a__: str , a__: int="" ): _UpperCAmelCase = line.decode('utf-8' ).rstrip() sink.append(a__ ) if not quiet: print(a__ , a__ , file=a__ ) # XXX: the timeout doesn't seem to make any difference here await asyncio.wait( [ asyncio.create_task(_read_stream(p.stdout , lambda a__ : tee(a__ , a__ , sys.stdout , label='stdout:' ) ) ), asyncio.create_task(_read_stream(p.stderr , lambda a__ : tee(a__ , a__ , sys.stderr , label='stderr:' ) ) ), ] , timeout=a__ , ) return _RunOutput(await p.wait() , a__ , a__ ) def lowerCAmelCase__ ( a__: Dict , a__: Union[str, Any]=None , a__: int=None , a__: List[Any]=1_8_0 , a__: Union[str, Any]=False , a__: Optional[int]=True ) -> _RunOutput: '''simple docstring''' _UpperCAmelCase = asyncio.get_event_loop() _UpperCAmelCase = loop.run_until_complete( _stream_subprocess(a__ , env=a__ , stdin=a__ , timeout=a__ , quiet=a__ , echo=a__ ) ) _UpperCAmelCase = ' '.join(a__ ) if result.returncode > 0: _UpperCAmelCase = '\n'.join(result.stderr ) raise RuntimeError( F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n''' F'''The combined stderr from workers follows:\n{stderr}''' ) return result class __a ( UpperCAmelCase ): pass def lowerCAmelCase__ ( a__: List[str] , a__: Union[str, Any]=False ) -> List[str]: '''simple docstring''' try: _UpperCAmelCase = subprocess.check_output(a__ , stderr=subprocess.STDOUT ) if return_stdout: if hasattr(a__ , 'decode' ): _UpperCAmelCase = output.decode('utf-8' ) return output except subprocess.CalledProcessError as e: raise SubprocessCallException( F'''Command `{" ".join(a__ )}` failed with the following error:\n\n{e.output.decode()}''' ) from e
329
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __a ( UpperCAmelCase ): _a : str = 'data2vec-text' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = position_embedding_type _UpperCAmelCase = use_cache _UpperCAmelCase = classifier_dropout class __a ( UpperCAmelCase ): @property def UpperCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
329
1
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) lowerCAmelCase__ :Any = '''\ Text data. Second line of data.''' lowerCAmelCase__ :List[str] = '''file''' @pytest.fixture(scope='session' ) def lowerCAmelCase__ ( a__: List[Any] ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = tmp_path_factory.mktemp('data' ) / (FILE_PATH + '.zstd') _UpperCAmelCase = bytes(a__ , 'utf-8' ) with zstd.open(a__ , 'wb' ) as f: f.write(a__ ) return path @pytest.fixture def lowerCAmelCase__ ( a__: int ) -> List[Any]: '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , a__ ) , 'w' ) as f: f.write(a__ ) return FILE_PATH @pytest.mark.parametrize('compression_format' , ['gzip', 'xz', 'zstd'] ) def lowerCAmelCase__ ( a__: Tuple , a__: List[str] , a__: Tuple , a__: Any , a__: str , a__: Tuple ) -> str: '''simple docstring''' _UpperCAmelCase = {'gzip': gz_file, 'xz': xz_file, 'zstd': zstd_path} _UpperCAmelCase = input_paths[compression_format] _UpperCAmelCase = tmp_path / 'cache' _UpperCAmelCase = DownloadConfig(cache_dir=a__ , extract_compressed_file=a__ ) _UpperCAmelCase = cached_path(a__ , download_config=a__ ) with open(a__ ) as f: _UpperCAmelCase = f.read() with open(a__ ) as f: _UpperCAmelCase = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize('default_extracted' , [True, False] ) @pytest.mark.parametrize('default_cache_dir' , [True, False] ) def lowerCAmelCase__ ( a__: str , a__: Any , a__: str , a__: Optional[int] , a__: Tuple ) -> Dict: '''simple docstring''' _UpperCAmelCase = 'custom_cache' _UpperCAmelCase = 'custom_extracted_dir' _UpperCAmelCase = tmp_path / 'custom_extracted_path' if default_extracted: _UpperCAmelCase = ('downloads' if default_cache_dir else custom_cache_dir, 'extracted') else: monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_DIR' , a__ ) monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(a__ ) ) _UpperCAmelCase = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) _UpperCAmelCase = xz_file _UpperCAmelCase = ( DownloadConfig(extract_compressed_file=a__ ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=a__ ) ) _UpperCAmelCase = cached_path(a__ , download_config=a__ ) assert Path(a__ ).parent.parts[-2:] == expected def lowerCAmelCase__ ( a__: Tuple ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = str(Path(a__ ).resolve() ) assert cached_path(a__ ) == text_file # relative path _UpperCAmelCase = str(Path(a__ ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(a__ ) == text_file def lowerCAmelCase__ ( a__: Any ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = str(tmp_path.resolve() / '__missing_file__.txt' ) with pytest.raises(a__ ): cached_path(a__ ) # relative path _UpperCAmelCase = './__missing_file__.txt' with pytest.raises(a__ ): cached_path(a__ ) def lowerCAmelCase__ ( a__: Dict ) -> int: '''simple docstring''' _UpperCAmelCase = get_from_cache(F'''tmp://{tmpfs_file}''' ) with open(a__ ) as f: _UpperCAmelCase = f.read() assert output_file_content == FILE_CONTENT @patch('datasets.config.HF_DATASETS_OFFLINE' , a__ ) def lowerCAmelCase__ ( ) -> int: '''simple docstring''' with pytest.raises(a__ ): cached_path('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , a__ ) def lowerCAmelCase__ ( a__: str ) -> Any: '''simple docstring''' _UpperCAmelCase = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(a__ ): http_get('https://huggingface.co' , temp_file=a__ ) with pytest.raises(a__ ): http_head('https://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , a__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(a__ ): ftp_get('ftp://huggingface.co' , temp_file=a__ ) with pytest.raises(a__ ): ftp_head('ftp://huggingface.co' ) @patch('datasets.config.HF_DATASETS_OFFLINE' , a__ ) def lowerCAmelCase__ ( a__: List[Any] ) -> Any: '''simple docstring''' _UpperCAmelCase = tmp_path_factory.mktemp('data' ) / 'file.html' with pytest.raises(a__ ): fsspec_get('s3://huggingface.co' , temp_file=a__ ) with pytest.raises(a__ ): fsspec_head('s3://huggingface.co' )
329
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> List[str]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = depths _UpperCAmelCase = num_heads _UpperCAmelCase = window_size _UpperCAmelCase = mlp_ratio _UpperCAmelCase = qkv_bias _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = hidden_act _UpperCAmelCase = use_absolute_embeddings _UpperCAmelCase = patch_norm _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = is_training _UpperCAmelCase = scope _UpperCAmelCase = use_labels _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = encoder_stride _UpperCAmelCase = out_features _UpperCAmelCase = out_indices def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _UpperCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = ['stem'] _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _a : str = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} _a : Optional[int] = False _a : List[str] = False _a : List[str] = False _a : Optional[int] = False _a : Tuple = False def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip('Swin does not use inputs_embeds' ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" pass @unittest.skip('Swin does not support feedforward chunking' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = 3 _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _UpperCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has''' f''' `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}.''' ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) @require_torch class __a ( unittest.TestCase , UpperCAmelCase ): _a : Any = (MaskFormerSwinBackbone,) if is_torch_available() else () _a : Any = MaskFormerSwinConfig def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: _UpperCAmelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
329
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any]=1_0 ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for _ in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCAmelCase__ ( a__: List[str] , a__: Any=1_0 ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [] for step in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(a__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , a__ ) _UpperCAmelCase = torch.load(a__ ) scheduler.load_state_dict(a__ ) return lrs @require_torch class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-3_0, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_SCREAMING_SNAKE_CASE , weight_decay=0.0 , relative_step=_SCREAMING_SNAKE_CASE , scale_parameter=_SCREAMING_SNAKE_CASE , warmup_init=_SCREAMING_SNAKE_CASE , ) for _ in range(1000 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __a ( unittest.TestCase ): _a : Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _a : Dict = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _a : List[Any] = 10 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE , msg=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListAlmostEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tol=1e-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_SCREAMING_SNAKE_CASE ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , msg=f'''failed for {scheduler_func} in save and reload''' ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = fn def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
329
from collections.abc import Generator def lowerCAmelCase__ ( ) -> Generator[int, None, None]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = 0, 1 while True: _UpperCAmelCase , _UpperCAmelCase = b, a + b yield b def lowerCAmelCase__ ( a__: int = 1_0_0_0 ) -> int: '''simple docstring''' _UpperCAmelCase = 1 _UpperCAmelCase = fibonacci_generator() while len(str(next(a__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
329
1
import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def lowerCAmelCase__ ( ) -> None: '''simple docstring''' print('Making key files...' ) make_key_files('rsa' , 1_0_2_4 ) print('Key files generation successful.' ) def lowerCAmelCase__ ( a__: int ) -> tuple[tuple[int, int], tuple[int, int]]: '''simple docstring''' print('Generating prime p...' ) _UpperCAmelCase = rabinMiller.generate_large_prime(a__ ) print('Generating prime q...' ) _UpperCAmelCase = rabinMiller.generate_large_prime(a__ ) _UpperCAmelCase = p * q print('Generating e that is relatively prime to (p - 1) * (q - 1)...' ) while True: _UpperCAmelCase = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(a__ , (p - 1) * (q - 1) ) == 1: break print('Calculating d that is mod inverse of e...' ) _UpperCAmelCase = cryptoMath.find_mod_inverse(a__ , (p - 1) * (q - 1) ) _UpperCAmelCase = (n, e) _UpperCAmelCase = (n, d) return (public_key, private_key) def lowerCAmelCase__ ( a__: str , a__: int ) -> None: '''simple docstring''' if os.path.exists(F'''{name}_pubkey.txt''' ) or os.path.exists(F'''{name}_privkey.txt''' ): print('\nWARNING:' ) print( F'''"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n''' 'Use a different name or delete these files and re-run this program.' ) sys.exit() _UpperCAmelCase , _UpperCAmelCase = generate_key(a__ ) print(F'''\nWriting public key to file {name}_pubkey.txt...''' ) with open(F'''{name}_pubkey.txt''' , 'w' ) as out_file: out_file.write(F'''{key_size},{public_key[0]},{public_key[1]}''' ) print(F'''Writing private key to file {name}_privkey.txt...''' ) with open(F'''{name}_privkey.txt''' , 'w' ) as out_file: out_file.write(F'''{key_size},{private_key[0]},{private_key[1]}''' ) if __name__ == "__main__": main()
329
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = SamImageProcessor() _UpperCAmelCase = SamProcessor(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ).image_processor def UpperCAmelCase__ ( self ) -> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCAmelCase = [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase = self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) _UpperCAmelCase = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='np' ) _UpperCAmelCase = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [torch.ones((1, 3, 5, 5) )] _UpperCAmelCase = [[1764, 2646]] _UpperCAmelCase = [[683, 1024]] _UpperCAmelCase = processor.post_process_masks(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , torch.tensor(_SCREAMING_SNAKE_CASE ) , torch.tensor(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np _UpperCAmelCase = [np.ones((1, 3, 5, 5) )] _UpperCAmelCase = processor.post_process_masks(_SCREAMING_SNAKE_CASE , np.array(_SCREAMING_SNAKE_CASE ) , np.array(_SCREAMING_SNAKE_CASE ) ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) _UpperCAmelCase = [[1, 0], [0, 1]] with self.assertRaises(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = processor.post_process_masks(_SCREAMING_SNAKE_CASE , np.array(_SCREAMING_SNAKE_CASE ) , np.array(_SCREAMING_SNAKE_CASE ) ) @require_vision @require_tf class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = SamImageProcessor() _UpperCAmelCase = SamProcessor(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ).image_processor def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCAmelCase = [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) _UpperCAmelCase = self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) _UpperCAmelCase = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_SCREAMING_SNAKE_CASE , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='np' ) _UpperCAmelCase = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [tf.ones((1, 3, 5, 5) )] _UpperCAmelCase = [[1764, 2646]] _UpperCAmelCase = [[683, 1024]] _UpperCAmelCase = processor.post_process_masks(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) , tf.convert_to_tensor(_SCREAMING_SNAKE_CASE ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) # should also work with np _UpperCAmelCase = [np.ones((1, 3, 5, 5) )] _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , np.array(_SCREAMING_SNAKE_CASE ) , np.array(_SCREAMING_SNAKE_CASE ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 1764, 2646) ) _UpperCAmelCase = [[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , np.array(_SCREAMING_SNAKE_CASE ) , np.array(_SCREAMING_SNAKE_CASE ) , return_tensors='tf' ) @require_vision @require_torchvision class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = tempfile.mkdtemp() _UpperCAmelCase = SamImageProcessor() _UpperCAmelCase = SamProcessor(_SCREAMING_SNAKE_CASE ) processor.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return AutoProcessor.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE ).image_processor def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _UpperCAmelCase = [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) _UpperCAmelCase = [tf.convert_to_tensor(_SCREAMING_SNAKE_CASE )] _UpperCAmelCase = [torch.tensor(_SCREAMING_SNAKE_CASE )] _UpperCAmelCase = [[1764, 2646]] _UpperCAmelCase = [[683, 1024]] _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='tf' ) _UpperCAmelCase = processor.post_process_masks( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.get_image_processor() _UpperCAmelCase = SamProcessor(image_processor=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.prepare_image_inputs() _UpperCAmelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='pt' )['pixel_values'].numpy() _UpperCAmelCase = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='pt' )['pixel_values'].numpy() _UpperCAmelCase = image_processor(_SCREAMING_SNAKE_CASE , return_tensors='tf' )['pixel_values'].numpy() _UpperCAmelCase = processor(images=_SCREAMING_SNAKE_CASE , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) )
329
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 20} _UpperCAmelCase = do_thumbnail _UpperCAmelCase = do_align_axis _UpperCAmelCase = do_pad _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = DonutImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DonutImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 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 , 'do_thumbnail' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_align_long_axis' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , )
329
1
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def lowerCAmelCase__ ( a__: Any ) -> Optional[Any]: '''simple docstring''' if ( (cp >= 0X4_e00 and cp <= 0X9_fff) or (cp >= 0X3_400 and cp <= 0X4_dbf) # or (cp >= 0X20_000 and cp <= 0X2a_6df) # or (cp >= 0X2a_700 and cp <= 0X2b_73f) # or (cp >= 0X2b_740 and cp <= 0X2b_81f) # or (cp >= 0X2b_820 and cp <= 0X2c_eaf) # or (cp >= 0Xf_900 and cp <= 0Xf_aff) or (cp >= 0X2f_800 and cp <= 0X2f_a1f) # ): # return True return False def lowerCAmelCase__ ( a__: str ) -> List[Any]: '''simple docstring''' for char in word: _UpperCAmelCase = ord(a__ ) if not _is_chinese_char(a__ ): return 0 return 1 def lowerCAmelCase__ ( a__: List[str] ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = set() for token in tokens: _UpperCAmelCase = len(a__ ) > 1 and is_chinese(a__ ) if chinese_word: word_set.add(a__ ) _UpperCAmelCase = list(a__ ) return word_list def lowerCAmelCase__ ( a__: List[str] , a__: set() ) -> str: '''simple docstring''' if not chinese_word_set: return bert_tokens _UpperCAmelCase = max([len(a__ ) for w in chinese_word_set] ) _UpperCAmelCase = bert_tokens _UpperCAmelCase , _UpperCAmelCase = 0, len(a__ ) while start < end: _UpperCAmelCase = True if is_chinese(bert_word[start] ): _UpperCAmelCase = min(end - start , a__ ) for i in range(a__ , 1 , -1 ): _UpperCAmelCase = ''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): _UpperCAmelCase = '##' + bert_word[j] _UpperCAmelCase = start + i _UpperCAmelCase = False break if single_word: start += 1 return bert_word def lowerCAmelCase__ ( a__: List[str] , a__: LTP , a__: BertTokenizer ) -> List[str]: '''simple docstring''' _UpperCAmelCase = [] for i in range(0 , len(a__ ) , 1_0_0 ): _UpperCAmelCase = ltp_tokenizer.seg(lines[i : i + 1_0_0] )[0] _UpperCAmelCase = [get_chinese_word(a__ ) for r in res] ltp_res.extend(a__ ) assert len(a__ ) == len(a__ ) _UpperCAmelCase = [] for i in range(0 , len(a__ ) , 1_0_0 ): _UpperCAmelCase = bert_tokenizer(lines[i : i + 1_0_0] , add_special_tokens=a__ , truncation=a__ , max_length=5_1_2 ) bert_res.extend(res['input_ids'] ) assert len(a__ ) == len(a__ ) _UpperCAmelCase = [] for input_ids, chinese_word in zip(a__ , a__ ): _UpperCAmelCase = [] for id in input_ids: _UpperCAmelCase = bert_tokenizer._convert_id_to_token(a__ ) input_tokens.append(a__ ) _UpperCAmelCase = add_sub_symbol(a__ , a__ ) _UpperCAmelCase = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(a__ ): if token[:2] == "##": _UpperCAmelCase = token[2:] # save chinese tokens' pos if len(a__ ) == 1 and _is_chinese_char(ord(a__ ) ): ref_id.append(a__ ) ref_ids.append(a__ ) assert len(a__ ) == len(a__ ) return ref_ids def lowerCAmelCase__ ( a__: Dict ) -> Dict: '''simple docstring''' with open(args.file_name , 'r' , encoding='utf-8' ) as f: _UpperCAmelCase = f.readlines() _UpperCAmelCase = [line.strip() for line in data if len(a__ ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' _UpperCAmelCase = LTP(args.ltp ) # faster in GPU device _UpperCAmelCase = BertTokenizer.from_pretrained(args.bert ) _UpperCAmelCase = prepare_ref(a__ , a__ , a__ ) with open(args.save_path , 'w' , encoding='utf-8' ) as f: _UpperCAmelCase = [json.dumps(a__ ) + '\n' for ref in ref_ids] f.writelines(a__ ) if __name__ == "__main__": lowerCAmelCase__ :Tuple = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') lowerCAmelCase__ :Optional[Any] = parser.parse_args() main(args)
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
from .configuration_bert_masked import MaskedBertConfig from .modeling_bert_masked import ( MaskedBertForMultipleChoice, MaskedBertForQuestionAnswering, MaskedBertForSequenceClassification, MaskedBertForTokenClassification, MaskedBertModel, ) from .modules import *
329
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
1
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) if self.framework != "pt": raise ValueError(f'''The {self.__class__} is only available in PyTorch.''' ) # No specific FOR_XXX available yet def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = {} if "candidate_labels" in kwargs: _UpperCAmelCase = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: _UpperCAmelCase = kwargs['hypothesis_template'] return preprocess_params, {}, {} def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE="This is a sound of {}." ) -> Optional[Any]: """simple docstring""" if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if audio.startswith('http://' ) or audio.startswith('https://' ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png _UpperCAmelCase = requests.get(_SCREAMING_SNAKE_CASE ).content else: with open(_SCREAMING_SNAKE_CASE , 'rb' ) as f: _UpperCAmelCase = f.read() if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = ffmpeg_read(_SCREAMING_SNAKE_CASE , self.feature_extractor.sampling_rate ) if not isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): raise ValueError('We expect a numpy ndarray as input' ) if len(audio.shape ) != 1: raise ValueError('We expect a single channel audio input for ZeroShotAudioClassificationPipeline' ) _UpperCAmelCase = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='pt' ) _UpperCAmelCase = candidate_labels _UpperCAmelCase = [hypothesis_template.format(_SCREAMING_SNAKE_CASE ) for x in candidate_labels] _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [text_inputs] return inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _UpperCAmelCase = model_inputs.pop('candidate_labels' ) _UpperCAmelCase = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = text_inputs[0] else: # Batching case. _UpperCAmelCase = text_inputs[0][0] _UpperCAmelCase = self.model(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_audio, } return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = model_outputs.pop('candidate_labels' ) _UpperCAmelCase = model_outputs['logits'][0] if self.framework == "pt": _UpperCAmelCase = logits.softmax(dim=0 ) _UpperCAmelCase = probs.tolist() else: raise ValueError('`tf` framework not supported.' ) _UpperCAmelCase = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) , key=lambda _SCREAMING_SNAKE_CASE : -x[0] ) ] return result
329
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
1
import unittest import numpy as np from diffusers import OnnxStableDiffusionInpaintPipelineLegacy from diffusers.utils.testing_utils import ( is_onnx_available, load_image, load_numpy, nightly, require_onnxruntime, require_torch_gpu, ) if is_onnx_available(): import onnxruntime as ort @nightly @require_onnxruntime @require_torch_gpu class __a ( unittest.TestCase ): @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = ort.SessionOptions() _UpperCAmelCase = False return options def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo.png' ) _UpperCAmelCase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/overture-creations-5sI6fQgYIuo_mask.png' ) _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy' ) # using the PNDM scheduler by default _UpperCAmelCase = OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_SCREAMING_SNAKE_CASE , feature_extractor=_SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 'A red cat sitting on a park bench' _UpperCAmelCase = np.random.RandomState(0 ) _UpperCAmelCase = pipe( prompt=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=15 , generator=_SCREAMING_SNAKE_CASE , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (512, 512, 3) assert np.abs(expected_image - image ).max() < 1e-2
329
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
1
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = False ) -> str: """simple docstring""" _UpperCAmelCase = scheduler _UpperCAmelCase = optimizers if isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ) else [optimizers] _UpperCAmelCase = split_batches _UpperCAmelCase = step_with_optimizer _UpperCAmelCase = GradientState() def UpperCAmelCase__ ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step _UpperCAmelCase = AcceleratorState().num_processes for _ in range(_SCREAMING_SNAKE_CASE ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , 'total_steps' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) else: self.scheduler.step(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" return self.scheduler.get_last_lr() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return self.scheduler.state_dict() def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.scheduler.load_state_dict(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" return self.scheduler.get_lr() def UpperCAmelCase__ ( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" return self.scheduler.print_lr(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
329
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _UpperCAmelCase = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE , os.listdir(_SCREAMING_SNAKE_CASE )[0] , 'snapshots' ) )] _UpperCAmelCase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 4 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1514745 ) < 1e-3 assert np.abs(np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 49947.875 ) < 5e-1 _UpperCAmelCase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_SCREAMING_SNAKE_CASE ) == num_samples def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05652401) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2383808.2) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = FlaxDDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = scheduler.create_state() _UpperCAmelCase = scheduler_state _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045043945) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2347693.5) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = jax.random.split(jax.random.PRNGKey(0 ) , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # With memory efficient attention _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , use_memory_efficient_attention=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
329
1
import os def lowerCAmelCase__ ( a__: Union[str, Any] ) -> int: '''simple docstring''' _UpperCAmelCase = len(grid[0] ) _UpperCAmelCase = len(a__ ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 0 # Check vertically, horizontally, diagonally at the same time (only works # for nxn grid) for i in range(a__ ): for j in range(n_rows - 3 ): _UpperCAmelCase = grid[j][i] * grid[j + 1][i] * grid[j + 2][i] * grid[j + 3][i] _UpperCAmelCase = grid[i][j] * grid[i][j + 1] * grid[i][j + 2] * grid[i][j + 3] # Left-to-right diagonal (\) product if i < n_columns - 3: _UpperCAmelCase = ( grid[i][j] * grid[i + 1][j + 1] * grid[i + 2][j + 2] * grid[i + 3][j + 3] ) # Right-to-left diagonal(/) product if i > 2: _UpperCAmelCase = ( grid[i][j] * grid[i - 1][j + 1] * grid[i - 2][j + 2] * grid[i - 3][j + 3] ) _UpperCAmelCase = max( a__ , a__ , a__ , a__ ) if max_product > largest: _UpperCAmelCase = max_product return largest def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = [] with open(os.path.dirname(a__ ) + '/grid.txt' ) as file: for line in file: grid.append(line.strip('\n' ).split(' ' ) ) _UpperCAmelCase = [[int(a__ ) for i in grid[j]] for j in range(len(a__ ) )] return largest_product(a__ ) if __name__ == "__main__": print(solution())
329
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(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ :int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} if prompt is not None: _UpperCAmelCase = prompt if generate_kwargs is not None: _UpperCAmelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _UpperCAmelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,' ' please use only one' ) _UpperCAmelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. ''' 'Note also that one single text can be provided for conditional image to text generation.' ) _UpperCAmelCase = self.model.config.model_type if model_type == "git": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids _UpperCAmelCase = [self.tokenizer.cls_token_id] + input_ids _UpperCAmelCase = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _UpperCAmelCase = None return model_inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs['input_ids'] ) ): _UpperCAmelCase = None if generate_kwargs is None: _UpperCAmelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _UpperCAmelCase = model_inputs.pop(self.model.main_input_name ) _UpperCAmelCase = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = [] for output_ids in model_outputs: _UpperCAmelCase = { 'generated_text': self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
329
1
lowerCAmelCase__ :Union[str, Any] = range(2, 2_0 + 1) lowerCAmelCase__ :int = [1_0**k for k in range(ks[-1] + 1)] lowerCAmelCase__ :dict[int, dict[int, list[list[int]]]] = {} def lowerCAmelCase__ ( a__: Optional[int] , a__: Union[str, Any] , a__: Union[str, Any] , a__: int ) -> Optional[Any]: '''simple docstring''' _UpperCAmelCase = sum(a_i[j] for j in range(a__ , len(a__ ) ) ) _UpperCAmelCase = sum(a_i[j] * base[j] for j in range(min(len(a__ ) , a__ ) ) ) _UpperCAmelCase , _UpperCAmelCase = 0, 0 _UpperCAmelCase = n - i _UpperCAmelCase = memo.get(a__ ) if sub_memo is not None: _UpperCAmelCase = sub_memo.get(a__ ) if jumps is not None and len(a__ ) > 0: # find and make the largest jump without going over _UpperCAmelCase = -1 for _k in range(len(a__ ) - 1 , -1 , -1 ): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: _UpperCAmelCase = _k break if max_jump >= 0: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = jumps[max_jump] # since the difference between jumps is cached, add c _UpperCAmelCase = diff + c for j in range(min(a__ , len(a__ ) ) ): _UpperCAmelCase , _UpperCAmelCase = divmod(a__ , 1_0 ) if new_c > 0: add(a__ , a__ , a__ ) else: _UpperCAmelCase = [] else: _UpperCAmelCase = {c: []} _UpperCAmelCase = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _UpperCAmelCase , _UpperCAmelCase = next_term(a__ , k - 1 , i + dn , a__ ) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _UpperCAmelCase , _UpperCAmelCase = compute(a__ , a__ , i + dn , a__ ) diff += _diff dn += terms_jumped _UpperCAmelCase = sub_memo[c] # keep jumps sorted by # of terms skipped _UpperCAmelCase = 0 while j < len(a__ ): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(a__ , (diff, dn, k) ) return (diff, dn) def lowerCAmelCase__ ( a__: List[Any] , a__: List[str] , a__: Tuple , a__: List[str] ) -> Optional[Any]: '''simple docstring''' if i >= n: return 0, i if k > len(a__ ): a_i.extend([0 for _ in range(k - len(a__ ) )] ) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) _UpperCAmelCase = i _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 0, 0, 0 for j in range(len(a__ ) ): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 _UpperCAmelCase = ds_c + ds_b diff += addend _UpperCAmelCase = 0 for j in range(a__ ): _UpperCAmelCase = a_i[j] + addend _UpperCAmelCase , _UpperCAmelCase = divmod(a__ , 1_0 ) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a__ , a__ , a__ ) return diff, i - start_i def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int] , a__: List[Any] ) -> Any: '''simple docstring''' for j in range(a__ , len(a__ ) ): _UpperCAmelCase = digits[j] + addend if s >= 1_0: _UpperCAmelCase , _UpperCAmelCase = divmod(a__ , 1_0 ) _UpperCAmelCase = addend // 1_0 + quotient else: _UpperCAmelCase = s _UpperCAmelCase = addend // 1_0 if addend == 0: break while addend > 0: _UpperCAmelCase , _UpperCAmelCase = divmod(a__ , 1_0 ) digits.append(a__ ) def lowerCAmelCase__ ( a__: int = 1_0**1_5 ) -> int: '''simple docstring''' _UpperCAmelCase = [1] _UpperCAmelCase = 1 _UpperCAmelCase = 0 while True: _UpperCAmelCase , _UpperCAmelCase = next_term(a__ , 2_0 , i + dn , a__ ) dn += terms_jumped if dn == n - i: break _UpperCAmelCase = 0 for j in range(len(a__ ) ): a_n += digits[j] * 1_0**j return a_n if __name__ == "__main__": print(f'''{solution() = }''')
329
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
1
from __future__ import annotations import copy import tempfile import unittest from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available from transformers.testing_utils import ( DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tensorflow_probability, require_tf, slow, ) from ..bert.test_modeling_bert import BertModelTester if is_tf_available(): from transformers import ( TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelForTableQuestionAnswering, TFAutoModelForTokenClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFFunnelBaseModel, TFFunnelModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, TFTapasForQuestionAnswering, ) from transformers.models.auto.modeling_tf_auto import ( TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_MAPPING, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST class __a ( UpperCAmelCase ): _a : Optional[int] = 'new-model' if is_tf_available(): class __a ( UpperCAmelCase ): _a : int = NewModelConfig @require_tf class __a ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 'bert-base-cased' _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = 'bert-base-cased' _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForPreTraining.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = TFAutoModelForCausalLM.from_pretrained(_SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = TFAutoModelForMaskedLM.from_pretrained(_SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = TFAutoModelForSeqaSeqLM.from_pretrained(_SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" for model_name in ["bert-base-uncased"]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForSequenceClassification.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" for model_name in ["bert-base-uncased"]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) @slow @require_tensorflow_probability def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]: _UpperCAmelCase = AutoConfig.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModelForTableQuestionAnswering.from_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = TFAutoModelForTableQuestionAnswering.from_pretrained( _SCREAMING_SNAKE_CASE , output_loading_info=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 14410 ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = TFAutoModelWithLMHead.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) self.assertEqual(model.num_parameters() , 14410 ) self.assertEqual(model.num_parameters(only_trainable=_SCREAMING_SNAKE_CASE ) , 14410 ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = TFAutoModel.from_pretrained('sgugger/funnel-random-tiny' ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = copy.deepcopy(model.config ) _UpperCAmelCase = ['FunnelBaseModel'] _UpperCAmelCase = TFAutoModel.from_config(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" try: AutoConfig.register('new-model' , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [ TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSequenceClassification, TFAutoModelForTokenClassification, ] for auto_class in auto_classes: with self.subTest(auto_class.__name__ ): # Wrong config class will raise an error with self.assertRaises(_SCREAMING_SNAKE_CASE ): auto_class.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) auto_class.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_SCREAMING_SNAKE_CASE ): auto_class.register(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Now that the config is registered, it can be used as any other config with the auto-API _UpperCAmelCase = BertModelTester(self ).get_config() _UpperCAmelCase = NewModelConfig(**tiny_config.to_dict() ) _UpperCAmelCase = auto_class.from_config(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = auto_class.from_pretrained(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) finally: if "new-model" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["new-model"] for mapping in ( TF_MODEL_MAPPING, TF_MODEL_FOR_PRETRAINING_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, ): if NewModelConfig in mapping._extra_content: del mapping._extra_content[NewModelConfig] def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , 'bert-base is not a local folder and is not a valid model identifier' ): _UpperCAmelCase = TFAutoModel.from_pretrained('bert-base' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): _UpperCAmelCase = TFAutoModel.from_pretrained(_SCREAMING_SNAKE_CASE , revision='aaaaaa' ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" with self.assertRaisesRegex( _SCREAMING_SNAKE_CASE , 'hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin' , ): _UpperCAmelCase = TFAutoModel.from_pretrained('hf-internal-testing/config-no-model' ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with self.assertRaisesRegex(_SCREAMING_SNAKE_CASE , 'Use `from_pt=True` to load this model' ): _UpperCAmelCase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-bert-pt-only' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) with RequestCounter() as counter: _UpperCAmelCase = TFAutoModel.from_pretrained('hf-internal-testing/tiny-random-bert' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 ) # With a sharded checkpoint _UpperCAmelCase = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) with RequestCounter() as counter: _UpperCAmelCase = TFAutoModel.from_pretrained('ArthurZ/tiny-random-bert-sharded' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
329
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
1
import argparse import torch from torch import nn from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration def lowerCAmelCase__ ( a__: str ) -> int: '''simple docstring''' _UpperCAmelCase = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def lowerCAmelCase__ ( a__: Union[str, Any] ) -> Optional[int]: '''simple docstring''' _UpperCAmelCase = list(s_dict.keys() ) for key in keys: if "transformer_layers" in key: _UpperCAmelCase = s_dict.pop(a__ ) elif "subsample" in key: _UpperCAmelCase = s_dict.pop(a__ ) def lowerCAmelCase__ ( a__: Optional[int] ) -> List[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = emb.weight.shape _UpperCAmelCase = nn.Linear(a__ , a__ , bias=a__ ) _UpperCAmelCase = emb.weight.data return lin_layer def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict ) -> Tuple: '''simple docstring''' _UpperCAmelCase = torch.load(a__ , map_location='cpu' ) _UpperCAmelCase = mam_aaa['args'] _UpperCAmelCase = mam_aaa['model'] _UpperCAmelCase = state_dict['decoder.output_projection.weight'] remove_ignore_keys_(a__ ) rename_keys(a__ ) _UpperCAmelCase = state_dict['decoder.embed_tokens.weight'].shape[0] _UpperCAmelCase = args.share_decoder_input_output_embed _UpperCAmelCase = [int(a__ ) for i in args.conv_kernel_sizes.split(',' )] _UpperCAmelCase = SpeechaTextConfig( vocab_size=a__ , max_source_positions=args.max_source_positions , max_target_positions=args.max_target_positions , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , num_conv_layers=len(a__ ) , conv_channels=args.conv_channels , conv_kernel_sizes=a__ , input_feat_per_channel=args.input_feat_per_channel , input_channels=args.input_channels , tie_word_embeddings=a__ , num_beams=5 , max_length=2_0_0 , use_cache=a__ , decoder_start_token_id=2 , early_stopping=a__ , ) _UpperCAmelCase = SpeechaTextForConditionalGeneration(a__ ) _UpperCAmelCase , _UpperCAmelCase = model.model.load_state_dict(a__ , strict=a__ ) if len(a__ ) > 0 and not set(a__ ) <= { "encoder.embed_positions.weights", "decoder.embed_positions.weights", }: raise ValueError( 'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights` are allowed to be missing,' F''' but all the following weights are missing {missing}''' ) if tie_embeds: _UpperCAmelCase = make_linear_from_emb(model.model.decoder.embed_tokens ) else: _UpperCAmelCase = lm_head_weights model.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('''--fairseq_path''', type=str, help='''Path to the fairseq model (.pt) file.''') parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') lowerCAmelCase__ :List[Any] = parser.parse_args() convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)
329
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
1
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch lowerCAmelCase__ :int = logging.get_logger(__name__) class __a ( UpperCAmelCase ): _a : Union[str, Any] = ['pixel_values'] def __init__( self , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = 1 / 255 , _SCREAMING_SNAKE_CASE = True , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True , **_SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" super().__init__(**_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = size if size is not None else {'shortest_edge': 224} _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = crop_size if crop_size is not None else {'height': 256, 'width': 256} _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE , param_name='crop_size' ) _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = resample _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_center_crop _UpperCAmelCase = crop_size _UpperCAmelCase = do_flip_channel_order def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = PIL.Image.BILINEAR , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) if "shortest_edge" not in size: raise ValueError(f'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}''' ) _UpperCAmelCase = 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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> np.ndarray: """simple docstring""" _UpperCAmelCase = 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()}''' ) return center_crop(_SCREAMING_SNAKE_CASE , size=(size['height'], size['width']) , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> np.ndarray: """simple docstring""" return flip_channel_order(_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = ChannelDimension.FIRST , **_SCREAMING_SNAKE_CASE , ) -> PIL.Image.Image: """simple docstring""" _UpperCAmelCase = do_resize if do_resize is not None else self.do_resize _UpperCAmelCase = resample if resample is not None else self.resample _UpperCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _UpperCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCAmelCase = do_center_crop if do_center_crop is not None else self.do_center_crop _UpperCAmelCase = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) _UpperCAmelCase = size if size is not None else self.size _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE , default_to_square=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = crop_size if crop_size is not None else self.crop_size _UpperCAmelCase = get_size_dict(_SCREAMING_SNAKE_CASE , param_name='crop_size' ) _UpperCAmelCase = 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_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) # All transformations expect numpy arrays. _UpperCAmelCase = [to_numpy_array(_SCREAMING_SNAKE_CASE ) for image in images] if do_resize: _UpperCAmelCase = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE ) for image in images] if do_center_crop: _UpperCAmelCase = [self.center_crop(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE ) for image in images] if do_rescale: _UpperCAmelCase = [self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: _UpperCAmelCase = [self.flip_channel_order(image=_SCREAMING_SNAKE_CASE ) for image in images] _UpperCAmelCase = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for image in images] _UpperCAmelCase = {'pixel_values': images} return BatchFeature(data=_SCREAMING_SNAKE_CASE , tensor_type=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = 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 ): _UpperCAmelCase = target_sizes.numpy() _UpperCAmelCase = [] for idx in range(len(_SCREAMING_SNAKE_CASE ) ): _UpperCAmelCase = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = logits.argmax(dim=1 ) _UpperCAmelCase = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
329
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = AutoConfig.from_pretrained(a__ ) _UpperCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=a__ ) _UpperCAmelCase = checkpoints.load_tax_checkpoint(a__ ) _UpperCAmelCase = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": _UpperCAmelCase = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": _UpperCAmelCase = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['encoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_global_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = tax_mlp_layer_norm _UpperCAmelCase = flax_model_encoder_layer_block # Only for layer 0: _UpperCAmelCase = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_global_rel_embedding # Assigning _UpperCAmelCase = tax_model['target']['encoder']['encoder_norm']['scale'] _UpperCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] _UpperCAmelCase = tax_enc_dec_attention_module['key']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['out']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['query']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['decoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_pre_attention_layer_norm _UpperCAmelCase = tax_enc_dec_attention_key _UpperCAmelCase = tax_enc_dec_attention_out _UpperCAmelCase = tax_enc_dec_attention_query _UpperCAmelCase = tax_enc_dec_attention_value _UpperCAmelCase = tax_cross_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = txa_mlp_layer_norm _UpperCAmelCase = flax_model_decoder_layer_block # Decoder Normalization _UpperCAmelCase = tax_model['target']['decoder']['decoder_norm']['scale'] _UpperCAmelCase = txa_decoder_norm # Only for layer 0: _UpperCAmelCase = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_decoder_rel_embedding # Token Embeddings _UpperCAmelCase = tax_model['target']['token_embedder']['embedding'] _UpperCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: _UpperCAmelCase = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(a__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path the T5X checkpoint.''' ) parser.add_argument('''--config_name''', default=None, type=str, required=True, help='''Config name of LongT5/T5 model.''') parser.add_argument( '''--flax_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output FLAX model.''' ) lowerCAmelCase__ :List[str] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
329
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) lowerCAmelCase__ :Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : str = 'ctrl' _a : Tuple = ['past_key_values'] _a : List[Any] = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=246534 , _SCREAMING_SNAKE_CASE=256 , _SCREAMING_SNAKE_CASE=1280 , _SCREAMING_SNAKE_CASE=8192 , _SCREAMING_SNAKE_CASE=48 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-6 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=True , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = dff _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = use_cache super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __a : @staticmethod def UpperCAmelCase__ ( *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" pass @is_pipeline_test @require_torch @require_vision class __a ( unittest.TestCase ): _a : List[Any] = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) _UpperCAmelCase = [ { 'image': Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'question': 'How many cats are there?', }, { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'question': 'How many cats are there?', }, ] return vqa_pipeline, examples def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _UpperCAmelCase = vqa_pipeline(_SCREAMING_SNAKE_CASE , top_k=1 ) self.assertEqual( _SCREAMING_SNAKE_CASE , [ [{'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}], [{'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}], ] , ) @require_torch def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) _UpperCAmelCase = './tests/fixtures/tests_samples/COCO/000000039769.png' _UpperCAmelCase = 'How many cats are there?' _UpperCAmelCase = vqa_pipeline(image=_SCREAMING_SNAKE_CASE , question='How many cats are there?' , top_k=2 ) self.assertEqual( _SCREAMING_SNAKE_CASE , [{'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}, {'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}] ) _UpperCAmelCase = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( _SCREAMING_SNAKE_CASE , [{'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}, {'score': ANY(_SCREAMING_SNAKE_CASE ), 'answer': ANY(_SCREAMING_SNAKE_CASE )}] ) @slow @require_torch def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = pipeline('visual-question-answering' , model='dandelin/vilt-b32-finetuned-vqa' ) _UpperCAmelCase = './tests/fixtures/tests_samples/COCO/000000039769.png' _UpperCAmelCase = 'How many cats are there?' _UpperCAmelCase = vqa_pipeline(image=_SCREAMING_SNAKE_CASE , question=_SCREAMING_SNAKE_CASE , top_k=2 ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE , decimals=4 ) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) _UpperCAmelCase = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE , decimals=4 ) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) _UpperCAmelCase = vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(_SCREAMING_SNAKE_CASE , decimals=4 ) , [[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2 , ) @require_tf @unittest.skip('Visual question answering not implemented in TF' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass
329
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=1 / 255 , _SCREAMING_SNAKE_CASE=True , ) -> Dict: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std _UpperCAmelCase = do_rescale _UpperCAmelCase = rescale_factor _UpperCAmelCase = do_pad def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False ) -> Any: """simple docstring""" if not batched: _UpperCAmelCase = image_inputs[0] if isinstance(_SCREAMING_SNAKE_CASE , Image.Image ): _UpperCAmelCase , _UpperCAmelCase = image.size else: _UpperCAmelCase , _UpperCAmelCase = image.shape[1], image.shape[2] if w < h: _UpperCAmelCase = int(self.size['shortest_edge'] * h / w ) _UpperCAmelCase = self.size['shortest_edge'] elif w > h: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = int(self.size['shortest_edge'] * w / h ) else: _UpperCAmelCase = self.size['shortest_edge'] _UpperCAmelCase = self.size['shortest_edge'] else: _UpperCAmelCase = [] for image in image_inputs: _UpperCAmelCase , _UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[0] )[0] _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : str = DeformableDetrImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DeformableDetrImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = 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 , 'do_rescale' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 1333} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_SCREAMING_SNAKE_CASE ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase , _UpperCAmelCase = self.image_processor_tester.get_expected_values(_SCREAMING_SNAKE_CASE , batched=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = 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, expected_height, expected_width, ) , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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 _UpperCAmelCase = image_processing(_SCREAMING_SNAKE_CASE , return_tensors='pt' ).pixel_values _UpperCAmelCase , _UpperCAmelCase = 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, ) , ) @slow def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'image_id': 39769, 'annotations': target} # encode them _UpperCAmelCase = DeformableDetrImageProcessor() _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) ) @slow def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: _UpperCAmelCase = json.loads(f.read() ) _UpperCAmelCase = {'file_name': '000000039769.png', 'image_id': 39769, 'segments_info': target} _UpperCAmelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them _UpperCAmelCase = DeformableDetrImageProcessor(format='coco_panoptic' ) _UpperCAmelCase = image_processing(images=_SCREAMING_SNAKE_CASE , annotations=_SCREAMING_SNAKE_CASE , masks_path=_SCREAMING_SNAKE_CASE , return_tensors='pt' ) # verify pixel values _UpperCAmelCase = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding['pixel_values'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _SCREAMING_SNAKE_CASE , atol=1e-4 ) ) # verify area _UpperCAmelCase = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _SCREAMING_SNAKE_CASE ) ) # verify boxes _UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _SCREAMING_SNAKE_CASE , atol=1e-3 ) ) # verify image_id _UpperCAmelCase = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _SCREAMING_SNAKE_CASE ) ) # verify is_crowd _UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _SCREAMING_SNAKE_CASE ) ) # verify class_labels _UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _SCREAMING_SNAKE_CASE ) ) # verify masks _UpperCAmelCase = 822873 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _SCREAMING_SNAKE_CASE ) # verify orig_size _UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _SCREAMING_SNAKE_CASE ) ) # verify size _UpperCAmelCase = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _SCREAMING_SNAKE_CASE ) )
329
1
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ :Any = False, False, False @dataclass class __a : _a : Optional[int] = None _a : bool = True _a : bool = True _a : Optional[str] = None # Automatically constructed _a : ClassVar[str] = "dict" _a : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) _a : str = field(default='Audio' , init=UpperCAmelCase , repr=UpperCAmelCase ) def __call__( self ) -> Union[str, Any]: """simple docstring""" return self.pa_type def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> dict: """simple docstring""" try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('To support encoding audio data, please install \'soundfile\'.' ) from err if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": None, "path": value} elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes _UpperCAmelCase = BytesIO() sf.write(_SCREAMING_SNAKE_CASE , value['array'] , value['sampling_rate'] , format='wav' ) return {"bytes": buffer.getvalue(), "path": None} elif value.get('path' ) is not None and os.path.isfile(value['path'] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('pcm' ): # "PCM" only has raw audio bytes if value.get('sampling_rate' ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('To use PCM files, please specify a \'sampling_rate\' in Audio object' ) if value.get('bytes' ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) _UpperCAmelCase = np.frombuffer(value['bytes'] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: _UpperCAmelCase = np.memmap(value['path'] , dtype='h' , mode='r' ).astype(np.floataa ) / 32767 _UpperCAmelCase = BytesIO(bytes() ) sf.write(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , value['sampling_rate'] , format='wav' ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('path' )} elif value.get('bytes' ) is not None or value.get('path' ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('bytes' ), "path": value.get('path' )} else: raise ValueError( f'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> dict: """simple docstring""" if not self.decode: raise RuntimeError('Decoding is disabled for this feature. Please use Audio(decode=True) instead.' ) _UpperCAmelCase , _UpperCAmelCase = (value['path'], BytesIO(value['bytes'] )) if value['bytes'] is not None else (value['path'], None) if path is None and file is None: raise ValueError(f'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError('To support decoding audio files, please install \'librosa\' and \'soundfile\'.' ) from err _UpperCAmelCase = xsplitext(_SCREAMING_SNAKE_CASE )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( 'Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ' 'You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ' ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( 'Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ' 'You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ' ) if file is None: _UpperCAmelCase = token_per_repo_id or {} _UpperCAmelCase = path.split('::' )[-1] try: _UpperCAmelCase = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL )['repo_id'] _UpperCAmelCase = token_per_repo_id[repo_id] except (ValueError, KeyError): _UpperCAmelCase = None with xopen(_SCREAMING_SNAKE_CASE , 'rb' , use_auth_token=_SCREAMING_SNAKE_CASE ) as f: _UpperCAmelCase , _UpperCAmelCase = sf.read(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase , _UpperCAmelCase = sf.read(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = array.T if self.mono: _UpperCAmelCase = librosa.to_mono(_SCREAMING_SNAKE_CASE ) if self.sampling_rate and self.sampling_rate != sampling_rate: _UpperCAmelCase = librosa.resample(_SCREAMING_SNAKE_CASE , orig_sr=_SCREAMING_SNAKE_CASE , target_sr=self.sampling_rate ) _UpperCAmelCase = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def UpperCAmelCase__ ( self ) -> Union["FeatureType", Dict[str, "FeatureType"]]: """simple docstring""" from .features import Value if self.decode: raise ValueError('Cannot flatten a decoded Audio feature.' ) return { "bytes": Value('binary' ), "path": Value('string' ), } def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> pa.StructArray: """simple docstring""" if pa.types.is_string(storage.type ): _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, storage] , ['bytes', 'path'] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) _UpperCAmelCase = pa.StructArray.from_arrays([storage, path_array] , ['bytes', 'path'] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('array' ): _UpperCAmelCase = pa.array([Audio().encode_example(_SCREAMING_SNAKE_CASE ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('bytes' ) >= 0: _UpperCAmelCase = storage.field('bytes' ) else: _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: _UpperCAmelCase = storage.field('path' ) else: _UpperCAmelCase = pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=pa.string() ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=storage.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> pa.StructArray: """simple docstring""" @no_op_if_value_is_null def path_to_bytes(_SCREAMING_SNAKE_CASE ): with xopen(_SCREAMING_SNAKE_CASE , 'rb' ) as f: _UpperCAmelCase = f.read() return bytes_ _UpperCAmelCase = pa.array( [ (path_to_bytes(x['path'] ) if x['bytes'] is None else x['bytes']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) _UpperCAmelCase = pa.array( [os.path.basename(_SCREAMING_SNAKE_CASE ) if path is not None else None for path in storage.field('path' ).to_pylist()] , type=pa.string() , ) _UpperCAmelCase = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null() ) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type )
329
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a ( unittest.TestCase ): _a : List[str] = JukeboxTokenizer _a : List[Any] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
329
1
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 __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : Any = VQModel _a : Tuple = 'sample' @property def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=(32, 32) ) -> Any: """simple docstring""" _UpperCAmelCase = 4 _UpperCAmelCase = 3 _UpperCAmelCase = floats_tensor((batch_size, num_channels) + sizes ).to(_SCREAMING_SNAKE_CASE ) return {"sample": image} @property def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" return (3, 32, 32) @property def UpperCAmelCase__ ( self ) -> str: """simple docstring""" return (3, 32, 32) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = { 'block_out_channels': [32, 64], 'in_channels': 3, 'out_channels': 3, 'down_block_types': ['DownEncoderBlock2D', 'DownEncoderBlock2D'], 'up_block_types': ['UpDecoderBlock2D', 'UpDecoderBlock2D'], 'latent_channels': 3, } _UpperCAmelCase = self.dummy_input return init_dict, inputs_dict def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = 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 ) _UpperCAmelCase = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = 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 ) _UpperCAmelCase = torch.randn(1 , model.config.in_channels , model.config.sample_size , model.config.sample_size ) _UpperCAmelCase = image.to(_SCREAMING_SNAKE_CASE ) with torch.no_grad(): _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ).sample _UpperCAmelCase = output[0, -1, -3:, -3:].flatten().cpu() # fmt: off _UpperCAmelCase = torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143] ) # fmt: on self.assertTrue(torch.allclose(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , atol=1e-3 ) )
329
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCAmelCase__ :Optional[int] = logging.getLogger(__name__) def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = argparse.ArgumentParser( description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.' ) parser.add_argument( '--dataset_name' , type=a__ , default='wikitext' , help='Name of the training. Explore datasets at: hf.co/datasets.' , ) parser.add_argument( '--dataset_config' , type=a__ , default='wikitext-103-raw-v1' , help='Configuration name of the dataset.' ) parser.add_argument( '--tokenizer_name_or_path' , type=a__ , default='sayakpaul/unigram-tokenizer-wikitext' , help='Tokenizer identifier. Can be a local filepath or a Hub identifier.' , ) parser.add_argument( '--shard_size' , type=a__ , default=1_0_0_0 , help='Number of entries to go in a single shard.' , ) parser.add_argument('--split' , type=a__ , default='train' , choices=['train', 'test', 'validation'] ) parser.add_argument( '--limit' , default=a__ , type=a__ , help='Limit the number of shards (used for debugging).' , ) parser.add_argument( '--max_length' , type=a__ , default=5_1_2 , help='Maximum sequence length. For training on TPUs, it helps to have a maximum' ' sequence length that is a multiple of 8.' , ) parser.add_argument( '--output_dir' , default='tf-tpu' , type=a__ , help='Output directory where the TFRecord shards will be saved. If the' ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord' ' shards will be directly saved to a Google Cloud Storage bucket.' , ) _UpperCAmelCase = parser.parse_args() return args def lowerCAmelCase__ ( a__: Union[str, Any] ) -> List[Any]: '''simple docstring''' def fn(a__: str ): return tokenizer(examples['text'] ) return fn def lowerCAmelCase__ ( a__: List[str] ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for i in range(len(tokenized_data['input_ids'] ) ): _UpperCAmelCase = { 'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i] ) ), 'attention_mask': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i] ) ), } _UpperCAmelCase = tf.train.Features(feature=a__ ) _UpperCAmelCase = tf.train.Example(features=a__ ) _UpperCAmelCase = example.SerializeToString() records.append(a__ ) return records def lowerCAmelCase__ ( a__: Union[str, Any] ) -> int: '''simple docstring''' _UpperCAmelCase = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: _UpperCAmelCase = min(len(a__ ) , args.limit ) _UpperCAmelCase = dataset.select(range(a__ ) ) print(F'''Limiting the dataset to {args.limit} entries.''' ) _UpperCAmelCase = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) _UpperCAmelCase = os.path.join(args.output_dir , args.split ) if not os.path.exists(a__ ): os.makedirs(a__ ) else: _UpperCAmelCase = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. _UpperCAmelCase = tokenize_function(a__ ) _UpperCAmelCase = dataset.map(a__ , batched=a__ , num_proc=4 , remove_columns=['text'] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(a__: Optional[int] ): # Concatenate all texts. _UpperCAmelCase = {k: sum(examples[k] , [] ) for k in examples.keys()} _UpperCAmelCase = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 _UpperCAmelCase = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. _UpperCAmelCase = { k: [t[i : i + args.max_length] for i in range(0 , a__ , args.max_length )] for k, t in concatenated_examples.items() } return result _UpperCAmelCase = dataset_tokenized.map(a__ , batched=a__ , batch_size=1_0_0_0 , num_proc=4 ) _UpperCAmelCase = 0 _UpperCAmelCase = 0 for shard in range(0 , len(a__ ) , args.shard_size ): _UpperCAmelCase = grouped_dataset[shard : shard + args.shard_size] _UpperCAmelCase = len(dataset_snapshot['input_ids'] ) _UpperCAmelCase = os.path.join(a__ , F'''dataset-{shard_count}-{records_containing}.tfrecord''' ) _UpperCAmelCase = get_serialized_examples(a__ ) with tf.io.TFRecordWriter(a__ ) as out_file: for i in range(len(a__ ) ): _UpperCAmelCase = serialized_examples[i] out_file.write(a__ ) print('Wrote file {} containing {} records'.format(a__ , a__ ) ) shard_count += 1 total_records += records_containing with open(F'''split-{args.split}-records-count.txt''' , 'w' ) as f: print(F'''Total {args.split} records: {total_records}''' , file=a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = parse_args() main(args)
329
1
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any]=1_0 ) -> Any: '''simple docstring''' _UpperCAmelCase = [] for _ in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def lowerCAmelCase__ ( a__: List[str] , a__: Any=1_0 ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = [] for step in range(a__ ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase = os.path.join(a__ , 'schedule.bin' ) torch.save(scheduler.state_dict() , a__ ) _UpperCAmelCase = torch.load(a__ ) scheduler.load_state_dict(a__ ) return lrs @require_torch class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = torch.tensor([0.1, -0.2, -0.1] , requires_grad=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.tensor([0.4, 0.2, -0.5] ) _UpperCAmelCase = nn.MSELoss() # No warmup, constant schedule, no gradient clipping _UpperCAmelCase = Adafactor( params=[w] , lr=1e-2 , eps=(1e-3_0, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=_SCREAMING_SNAKE_CASE , weight_decay=0.0 , relative_step=_SCREAMING_SNAKE_CASE , scale_parameter=_SCREAMING_SNAKE_CASE , warmup_init=_SCREAMING_SNAKE_CASE , ) for _ in range(1000 ): _UpperCAmelCase = criterion(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class __a ( unittest.TestCase ): _a : Dict = nn.Linear(50 , 50 ) if is_torch_available() else None _a : Dict = AdamW(m.parameters() , lr=1_0.0 ) if is_torch_available() else None _a : List[Any] = 10 def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> str: """simple docstring""" self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , len(_SCREAMING_SNAKE_CASE ) ) for a, b in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): self.assertAlmostEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , delta=_SCREAMING_SNAKE_CASE , msg=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = {'num_warmup_steps': 2, 'num_training_steps': 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) _UpperCAmelCase = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'num_warmup_steps': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, 'num_cycles': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, 'power': 2.0, 'lr_end': 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'num_warmup_steps': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): _UpperCAmelCase , _UpperCAmelCase = data _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) _UpperCAmelCase = unwrap_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListAlmostEqual( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , tol=1e-2 , msg=f'''failed for {scheduler_func} in normal scheduler''' , ) _UpperCAmelCase = scheduler_func(self.optimizer , **_SCREAMING_SNAKE_CASE ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(_SCREAMING_SNAKE_CASE ) # wrap to test picklability of the schedule _UpperCAmelCase = unwrap_and_save_reload_schedule(_SCREAMING_SNAKE_CASE , self.num_steps ) self.assertListEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , msg=f'''failed for {scheduler_func} in save and reload''' ) class __a : def __init__( self , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = fn def __call__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" return self.fn(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) @classmethod def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = list(map(self , scheduler.lr_lambdas ) )
329
1
import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline lowerCAmelCase__ :int = datasets.utils.logging.get_logger(__name__) @dataclass class __a ( datasets.BuilderConfig ): _a : Optional[datasets.Features] = None _a : str = "utf-8" _a : Optional[str] = None _a : Optional[str] = None _a : bool = True # deprecated _a : Optional[int] = None # deprecated _a : int = 10 << 20 # 10MB _a : Optional[bool] = None class __a ( datasets.ArrowBasedBuilder ): _a : List[str] = JsonConfig def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" if self.config.block_size is not None: logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead' ) _UpperCAmelCase = self.config.block_size if self.config.use_threads is not True: logger.warning( 'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.' ) if self.config.newlines_in_values is not None: raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported' ) return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" if not self.config.data_files: raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}''' ) _UpperCAmelCase = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_SCREAMING_SNAKE_CASE , (str, list, tuple) ): _UpperCAmelCase = data_files if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = [files] _UpperCAmelCase = [dl_manager.iter_files(_SCREAMING_SNAKE_CASE ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'files': files} )] _UpperCAmelCase = [] for split_name, files in data_files.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = [files] _UpperCAmelCase = [dl_manager.iter_files(_SCREAMING_SNAKE_CASE ) for file in files] splits.append(datasets.SplitGenerator(name=_SCREAMING_SNAKE_CASE , gen_kwargs={'files': files} ) ) return splits def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> pa.Table: """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): _UpperCAmelCase = self.config.features.arrow_schema.field(_SCREAMING_SNAKE_CASE ).type _UpperCAmelCase = pa_table.append_column(_SCREAMING_SNAKE_CASE , pa.array([None] * len(_SCREAMING_SNAKE_CASE ) , type=_SCREAMING_SNAKE_CASE ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example _UpperCAmelCase = table_cast(_SCREAMING_SNAKE_CASE , self.config.features.arrow_schema ) return pa_table def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(_SCREAMING_SNAKE_CASE ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(_SCREAMING_SNAKE_CASE , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) # We keep only the field we are interested in _UpperCAmelCase = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): _UpperCAmelCase = set().union(*[row.keys() for row in dataset] ) _UpperCAmelCase = {col: [row.get(_SCREAMING_SNAKE_CASE ) for row in dataset] for col in keys} else: _UpperCAmelCase = dataset _UpperCAmelCase = pa.Table.from_pydict(_SCREAMING_SNAKE_CASE ) yield file_idx, self._cast_table(_SCREAMING_SNAKE_CASE ) # If the file has one json object per line else: with open(_SCREAMING_SNAKE_CASE , 'rb' ) as f: _UpperCAmelCase = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small _UpperCAmelCase = max(self.config.chunksize // 32 , 16 << 10 ) _UpperCAmelCase = ( self.config.encoding_errors if self.config.encoding_errors is not None else 'strict' ) while True: _UpperCAmelCase = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(_SCREAMING_SNAKE_CASE ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": _UpperCAmelCase = batch.decode(self.config.encoding , errors=_SCREAMING_SNAKE_CASE ).encode('utf-8' ) try: while True: try: _UpperCAmelCase = paj.read_json( io.BytesIO(_SCREAMING_SNAKE_CASE ) , read_options=paj.ReadOptions(block_size=_SCREAMING_SNAKE_CASE ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(_SCREAMING_SNAKE_CASE , pa.ArrowInvalid ) and "straddling" not in str(_SCREAMING_SNAKE_CASE ) or block_size > len(_SCREAMING_SNAKE_CASE ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f'''Batch of {len(_SCREAMING_SNAKE_CASE )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.''' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( _SCREAMING_SNAKE_CASE , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: _UpperCAmelCase = json.load(_SCREAMING_SNAKE_CASE ) except json.JSONDecodeError: logger.error(f'''Failed to read file \'{file}\' with error {type(_SCREAMING_SNAKE_CASE )}: {e}''' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # list is the only sequence type supported in JSON try: _UpperCAmelCase = set().union(*[row.keys() for row in dataset] ) _UpperCAmelCase = {col: [row.get(_SCREAMING_SNAKE_CASE ) for row in dataset] for col in keys} _UpperCAmelCase = pa.Table.from_pydict(_SCREAMING_SNAKE_CASE ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f'''Failed to read file \'{file}\' with error {type(_SCREAMING_SNAKE_CASE )}: {e}''' ) raise ValueError(f'''Not able to read records in the JSON file at {file}.''' ) from None yield file_idx, self._cast_table(_SCREAMING_SNAKE_CASE ) break else: logger.error(f'''Failed to read file \'{file}\' with error {type(_SCREAMING_SNAKE_CASE )}: {e}''' ) raise ValueError( f'''Not able to read records in the JSON file at {file}. ''' f'''You should probably indicate the field of the JSON file containing your records. ''' f'''This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ''' f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ''' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_SCREAMING_SNAKE_CASE ) batch_idx += 1
329
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import PoolFormerConfig, PoolFormerForImageClassification, PoolFormerImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ :Any = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: List[Any] , a__: Union[str, Any] , a__: Dict , a__: Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' _UpperCAmelCase = original_name.split('.' )[0] _UpperCAmelCase = key.split('.' ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 2] ) _UpperCAmelCase = int(key_list[key_list.index(a__ ) - 1] ) _UpperCAmelCase = orig_block_num - offset _UpperCAmelCase = key.replace(F'''{orig_block_num}.{layer_num}.{original_name}''' , F'''block.{new_block_num}.{layer_num}.{new_name}''' ) return key def lowerCAmelCase__ ( a__: Tuple ) -> int: '''simple docstring''' _UpperCAmelCase = OrderedDict() _UpperCAmelCase , _UpperCAmelCase = 0, 0 for key, value in state_dict.items(): if key.startswith('network' ): _UpperCAmelCase = key.replace('network' , 'poolformer.encoder' ) if "proj" in key: # Works for the first embedding as well as the internal embedding layers if key.endswith('bias' ) and "patch_embed" not in key: patch_emb_offset += 1 _UpperCAmelCase = key[: key.find('proj' )] _UpperCAmelCase = key.replace(a__ , F'''patch_embeddings.{total_embed_found}.''' ) _UpperCAmelCase = key.replace('proj' , 'projection' ) if key.endswith('bias' ): total_embed_found += 1 if "patch_embeddings" in key: _UpperCAmelCase = 'poolformer.encoder.' + key if "mlp.fc1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc1' , 'output.conv1' ) if "mlp.fc2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'mlp.fc2' , 'output.conv2' ) if "norm1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm1' , 'before_norm' ) if "norm2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'norm2' , 'after_norm' ) if "layer_scale_1" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_1' , 'layer_scale_1' ) if "layer_scale_2" in key: _UpperCAmelCase = replace_key_with_offset(a__ , a__ , 'layer_scale_2' , 'layer_scale_2' ) if "head" in key: _UpperCAmelCase = key.replace('head' , 'classifier' ) _UpperCAmelCase = value return new_state_dict def lowerCAmelCase__ ( ) -> Tuple: '''simple docstring''' _UpperCAmelCase = 'http://images.cocodataset.org/val2017/000000039769.jpg' _UpperCAmelCase = Image.open(requests.get(a__ , stream=a__ ).raw ) return image @torch.no_grad() def lowerCAmelCase__ ( a__: Optional[int] , a__: Dict , a__: Any ) -> Dict: '''simple docstring''' _UpperCAmelCase = PoolFormerConfig() # set attributes based on model_name _UpperCAmelCase = 'huggingface/label-files' _UpperCAmelCase = model_name[-3:] _UpperCAmelCase = 1_0_0_0 _UpperCAmelCase = 'imagenet-1k-id2label.json' _UpperCAmelCase = (1, 1_0_0_0) # set config attributes _UpperCAmelCase = json.load(open(hf_hub_download(a__ , a__ , repo_type='dataset' ) , 'r' ) ) _UpperCAmelCase = {int(a__ ): v for k, v in idalabel.items()} _UpperCAmelCase = idalabel _UpperCAmelCase = {v: k for k, v in idalabel.items()} if size == "s12": _UpperCAmelCase = [2, 2, 6, 2] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s24": _UpperCAmelCase = [4, 4, 1_2, 4] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 0.9 elif size == "s36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [6_4, 1_2_8, 3_2_0, 5_1_2] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.9 elif size == "m36": _UpperCAmelCase = [6, 6, 1_8, 6] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 elif size == "m48": _UpperCAmelCase = [8, 8, 2_4, 8] _UpperCAmelCase = [9_6, 1_9_2, 3_8_4, 7_6_8] _UpperCAmelCase = 4.0 _UpperCAmelCase = 1e-6 _UpperCAmelCase = 0.95 else: raise ValueError(F'''Size {size} not supported''' ) # load image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) # Prepare image _UpperCAmelCase = prepare_img() _UpperCAmelCase = image_processor(images=a__ , return_tensors='pt' ).pixel_values logger.info(F'''Converting model {model_name}...''' ) # load original state dict _UpperCAmelCase = torch.load(a__ , map_location=torch.device('cpu' ) ) # rename keys _UpperCAmelCase = rename_keys(a__ ) # create HuggingFace model and load state dict _UpperCAmelCase = PoolFormerForImageClassification(a__ ) model.load_state_dict(a__ ) model.eval() # Define image processor _UpperCAmelCase = PoolFormerImageProcessor(crop_pct=a__ ) _UpperCAmelCase = image_processor(images=prepare_img() , return_tensors='pt' ).pixel_values # forward pass _UpperCAmelCase = model(a__ ) _UpperCAmelCase = outputs.logits # define expected logit slices for different models if size == "s12": _UpperCAmelCase = torch.tensor([-0.3_045, -0.6_758, -0.4_869] ) elif size == "s24": _UpperCAmelCase = torch.tensor([0.4_402, -0.1_374, -0.8_045] ) elif size == "s36": _UpperCAmelCase = torch.tensor([-0.6_080, -0.5_133, -0.5_898] ) elif size == "m36": _UpperCAmelCase = torch.tensor([0.3_952, 0.2_263, -1.2_668] ) elif size == "m48": _UpperCAmelCase = torch.tensor([0.1_167, -0.0_656, -0.3_423] ) else: raise ValueError(F'''Size {size} not supported''' ) # verify logits assert logits.shape == expected_shape assert torch.allclose(logits[0, :3] , a__ , atol=1e-2 ) # finally, save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(a__ ).mkdir(exist_ok=a__ ) model.save_pretrained(a__ ) print(F'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :str = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''poolformer_s12''', type=str, help='''Name of the model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default=None, type=str, help='''Path to the original PyTorch checkpoint (.pth file).''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) lowerCAmelCase__ :Dict = parser.parse_args() convert_poolformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
329
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = process _UpperCAmelCase = params def __len__( self ) -> Union[str, Any]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = self.dataset[i] _UpperCAmelCase = self.process(_SCREAMING_SNAKE_CASE , **self.params ) return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = loader _UpperCAmelCase = infer _UpperCAmelCase = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether _UpperCAmelCase = None _UpperCAmelCase = loader_batch_size # Internal bookkeeping _UpperCAmelCase = None _UpperCAmelCase = None def __len__( self ) -> Any: """simple docstring""" return len(self.loader ) def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice _UpperCAmelCase = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) _UpperCAmelCase = {} for k, element in self._loader_batch_data.items(): if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Convert ModelOutput to tuple first _UpperCAmelCase = element.to_tuple() if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): _UpperCAmelCase = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): _UpperCAmelCase = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around _UpperCAmelCase = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers _UpperCAmelCase = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. _UpperCAmelCase = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 _UpperCAmelCase = self._loader_batch_data.__class__(_SCREAMING_SNAKE_CASE ) self._loader_batch_index += 1 return result def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch _UpperCAmelCase = next(self.iterator ) _UpperCAmelCase = self.infer(_SCREAMING_SNAKE_CASE , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size # Setting internal index to unwrap the batch _UpperCAmelCase = processed _UpperCAmelCase = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> Tuple: """simple docstring""" super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __iter__( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) _UpperCAmelCase = None return self def UpperCAmelCase__ ( self ) -> int: """simple docstring""" if self.subiterator is None: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item _UpperCAmelCase = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) _UpperCAmelCase = next(self.subiterator ) return processed class __a ( UpperCAmelCase ): def __iter__( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = iter(self.loader ) return self def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = False _UpperCAmelCase = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator while not is_last: _UpperCAmelCase = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): _UpperCAmelCase = processed else: _UpperCAmelCase = list(processed.keys() )[0] _UpperCAmelCase = processed[key] if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = len(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. _UpperCAmelCase = observed_batch_size _UpperCAmelCase = processed _UpperCAmelCase = 0 while self._loader_batch_index < self.loader_batch_size: _UpperCAmelCase = self.loader_batch_item() _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) if is_last: return accumulator else: _UpperCAmelCase = processed _UpperCAmelCase = item.pop('is_last' ) accumulator.append(_SCREAMING_SNAKE_CASE ) return accumulator class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = key def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return self.dataset[i][self.key] class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = dataset _UpperCAmelCase = keya _UpperCAmelCase = keya def __len__( self ) -> Optional[int]: """simple docstring""" return len(self.dataset ) def __getitem__( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
329
1
from ..utils import DummyObject, requires_backends class __a ( metaclass=UpperCAmelCase ): _a : str = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __a ( metaclass=UpperCAmelCase ): _a : Optional[Any] = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __a ( metaclass=UpperCAmelCase ): _a : Dict = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __a ( metaclass=UpperCAmelCase ): _a : str = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __a ( metaclass=UpperCAmelCase ): _a : Any = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class __a ( metaclass=UpperCAmelCase ): _a : Optional[int] = ['torch', 'transformers', 'onnx'] def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def UpperCAmelCase__ ( cls , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" requires_backends(cls , ['torch', 'transformers', 'onnx'] )
329
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase__ :int = logging.get_logger(__name__) lowerCAmelCase__ :Optional[Any] = { '''facebook/data2vec-text-base''': '''https://huggingface.co/data2vec/resolve/main/config.json''', } class __a ( UpperCAmelCase ): _a : str = 'data2vec-text' def __init__( self , _SCREAMING_SNAKE_CASE=30522 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=3072 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-1_2 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE="absolute" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE , ) -> List[Any]: """simple docstring""" super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = vocab_size _UpperCAmelCase = hidden_size _UpperCAmelCase = num_hidden_layers _UpperCAmelCase = num_attention_heads _UpperCAmelCase = hidden_act _UpperCAmelCase = intermediate_size _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = max_position_embeddings _UpperCAmelCase = type_vocab_size _UpperCAmelCase = initializer_range _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = position_embedding_type _UpperCAmelCase = use_cache _UpperCAmelCase = classifier_dropout class __a ( UpperCAmelCase ): @property def UpperCAmelCase__ ( self ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": _UpperCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
329
1
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class __a ( UpperCAmelCase ): _a : List[Any] = '' _a : Optional[int] = 'hf-legacy' # "hf://"" is reserved for hffs def __init__( self , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" super().__init__(self , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = repo_info _UpperCAmelCase = token _UpperCAmelCase = None def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" if self.dir_cache is None: _UpperCAmelCase = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes _UpperCAmelCase = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(_SCREAMING_SNAKE_CASE ): {'name': str(_SCREAMING_SNAKE_CASE ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = "rb" , **_SCREAMING_SNAKE_CASE , ) -> List[str]: """simple docstring""" if not isinstance(self.repo_info , _SCREAMING_SNAKE_CASE ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) _UpperCAmelCase = hf_hub_url(self.repo_info.id , _SCREAMING_SNAKE_CASE , revision=self.repo_info.sha ) return fsspec.open( _SCREAMING_SNAKE_CASE , mode=_SCREAMING_SNAKE_CASE , headers=get_authentication_headers_for_url(_SCREAMING_SNAKE_CASE , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" self._get_dirs() _UpperCAmelCase = self._strip_protocol(_SCREAMING_SNAKE_CASE ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" self._get_dirs() _UpperCAmelCase = PurePosixPath(path.strip('/' ) ) _UpperCAmelCase = {} for p, f in self.dir_cache.items(): _UpperCAmelCase = PurePosixPath(p.strip('/' ) ) _UpperCAmelCase = p.parent if root == path: _UpperCAmelCase = f _UpperCAmelCase = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
329
import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __a : def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=13 , _SCREAMING_SNAKE_CASE=32 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=[1, 2, 1] , _SCREAMING_SNAKE_CASE=[2, 2, 4] , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=10 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=["stage1", "stage2", "stage3"] , _SCREAMING_SNAKE_CASE=[1, 2, 3] , ) -> List[str]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = image_size _UpperCAmelCase = patch_size _UpperCAmelCase = num_channels _UpperCAmelCase = embed_dim _UpperCAmelCase = depths _UpperCAmelCase = num_heads _UpperCAmelCase = window_size _UpperCAmelCase = mlp_ratio _UpperCAmelCase = qkv_bias _UpperCAmelCase = hidden_dropout_prob _UpperCAmelCase = attention_probs_dropout_prob _UpperCAmelCase = drop_path_rate _UpperCAmelCase = hidden_act _UpperCAmelCase = use_absolute_embeddings _UpperCAmelCase = patch_norm _UpperCAmelCase = layer_norm_eps _UpperCAmelCase = initializer_range _UpperCAmelCase = is_training _UpperCAmelCase = scope _UpperCAmelCase = use_labels _UpperCAmelCase = type_sequence_label_size _UpperCAmelCase = encoder_stride _UpperCAmelCase = out_features _UpperCAmelCase = out_indices def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCAmelCase = None if self.use_labels: _UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _UpperCAmelCase = self.get_config() return config, pixel_values, labels def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModel(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) _UpperCAmelCase = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = ['stem'] _UpperCAmelCase = MaskFormerSwinBackbone(config=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.prepare_config_and_inputs() _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = config_and_inputs _UpperCAmelCase = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : int = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) _a : str = {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {} _a : Optional[int] = False _a : List[str] = False _a : List[str] = False _a : Optional[int] = False _a : Tuple = False def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) _UpperCAmelCase = ConfigTester(self , config_class=_SCREAMING_SNAKE_CASE , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" return def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_SCREAMING_SNAKE_CASE ) @unittest.skip('Swin does not use inputs_embeds' ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" pass @unittest.skip('Swin does not support feedforward chunking' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_SCREAMING_SNAKE_CASE , nn.Linear ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCAmelCase = [*signature.parameters.keys()] _UpperCAmelCase = ['pixel_values'] self.assertListEqual(arg_names[:1] , _SCREAMING_SNAKE_CASE ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() with torch.no_grad(): _UpperCAmelCase = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = outputs.hidden_states _UpperCAmelCase = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) # Swin has a different seq_length _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = 3 _UpperCAmelCase = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) _UpperCAmelCase = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) _UpperCAmelCase = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) _UpperCAmelCase = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCAmelCase = True self.check_hidden_states_output(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = 0 return t def check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE={} ): with torch.no_grad(): _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(**_SCREAMING_SNAKE_CASE , return_dict=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ).to_tuple() def recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if isinstance(_SCREAMING_SNAKE_CASE , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , set_nan_tensor_to_zero(_SCREAMING_SNAKE_CASE ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' f''' {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}. Dict has''' f''' `nan`: {torch.isnan(_SCREAMING_SNAKE_CASE ).any()} and `inf`: {torch.isinf(_SCREAMING_SNAKE_CASE )}.''' ) , ) recursive_check(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: _UpperCAmelCase = model_class(_SCREAMING_SNAKE_CASE ) model.to(_SCREAMING_SNAKE_CASE ) model.eval() _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._prepare_for_class(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , return_labels=_SCREAMING_SNAKE_CASE ) check_equivalence(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , {'output_hidden_states': True} ) @require_torch class __a ( unittest.TestCase , UpperCAmelCase ): _a : Any = (MaskFormerSwinBackbone,) if is_torch_available() else () _a : Any = MaskFormerSwinConfig def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase = MaskFormerSwinModelTester(self ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() _UpperCAmelCase = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: _UpperCAmelCase = backbone_class(_SCREAMING_SNAKE_CASE ) backbone.to(_SCREAMING_SNAKE_CASE ) backbone.eval() _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _SCREAMING_SNAKE_CASE ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_hidden_states=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: _UpperCAmelCase = backbone(**_SCREAMING_SNAKE_CASE , output_attentions=_SCREAMING_SNAKE_CASE ) self.assertIsNotNone(outputs.attentions )
329
1
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class __a ( unittest.TestCase ): _a : List[str] = JukeboxTokenizer _a : List[Any] = { 'artist': 'Zac Brown Band', 'genres': 'Country', 'lyrics': 'I met a traveller from an antique land,\n Who said "Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ', } @require_torch def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 7169, 507, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), torch.tensor([[0, 0, 0, 1069, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" import torch _UpperCAmelCase = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) _UpperCAmelCase = tokenizer(**self.metas )['input_ids'] # fmt: off _UpperCAmelCase = [ torch.tensor([[ 0, 0, 0, 1069, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1069, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
329
from collections.abc import Generator def lowerCAmelCase__ ( ) -> Generator[int, None, None]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = 0, 1 while True: _UpperCAmelCase , _UpperCAmelCase = b, a + b yield b def lowerCAmelCase__ ( a__: int = 1_0_0_0 ) -> int: '''simple docstring''' _UpperCAmelCase = 1 _UpperCAmelCase = fibonacci_generator() while len(str(next(a__ ) ) ) < n: answer += 1 return answer + 1 if __name__ == "__main__": print(solution(int(str(input()).strip())))
329
1
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib lowerCAmelCase__ :int = get_logger() lowerCAmelCase__ :Optional[dict] = None class __a ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" super().__init__(features=_SCREAMING_SNAKE_CASE ) import jax from jaxlib.xla_client import Device if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Expected {device} to be a `str` not {type(_SCREAMING_SNAKE_CASE )}, as `jaxlib.xla_extension.Device` ''' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) _UpperCAmelCase = device if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _UpperCAmelCase = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( f'''Device with string identifier {self.device} not listed among the available ''' f'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' f'''device: {str(jax.devices()[0] )}.''' ) _UpperCAmelCase = str(jax.devices()[0] ) _UpperCAmelCase = jnp_array_kwargs @staticmethod def UpperCAmelCase__ ( ) -> Dict[str, "jaxlib.xla_extension.Device"]: """simple docstring""" import jax return {str(_SCREAMING_SNAKE_CASE ): device for device in jax.devices()} def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" import jax import jax.numpy as jnp if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and column: if all( isinstance(_SCREAMING_SNAKE_CASE , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(_SCREAMING_SNAKE_CASE , axis=0 ) return column def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" import jax import jax.numpy as jnp if isinstance(_SCREAMING_SNAKE_CASE , (str, bytes, type(_SCREAMING_SNAKE_CASE )) ): return value elif isinstance(_SCREAMING_SNAKE_CASE , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() _UpperCAmelCase = {} if isinstance(_SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: _UpperCAmelCase = {'dtype': jnp.intaa} else: _UpperCAmelCase = {'dtype': jnp.intaa} elif isinstance(_SCREAMING_SNAKE_CASE , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): _UpperCAmelCase = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image ): _UpperCAmelCase = np.asarray(_SCREAMING_SNAKE_CASE ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: _UpperCAmelCase = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(_SCREAMING_SNAKE_CASE , **{**default_dtype, **self.jnp_array_kwargs} ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(_SCREAMING_SNAKE_CASE , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(_SCREAMING_SNAKE_CASE , '__array__' ) and not isinstance(_SCREAMING_SNAKE_CASE , jax.Array ): _UpperCAmelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(_SCREAMING_SNAKE_CASE , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) elif isinstance(_SCREAMING_SNAKE_CASE , (list, tuple) ): return self._consolidate([self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for substruct in data_struct] ) return self._tensorize(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: """simple docstring""" return map_nested(self._recursive_tensorize , _SCREAMING_SNAKE_CASE , map_list=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Mapping: """simple docstring""" _UpperCAmelCase = self.numpy_arrow_extractor().extract_row(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.python_features_decoder.decode_row(_SCREAMING_SNAKE_CASE ) return self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> "jax.Array": """simple docstring""" _UpperCAmelCase = self.numpy_arrow_extractor().extract_column(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.python_features_decoder.decode_column(_SCREAMING_SNAKE_CASE , pa_table.column_names[0] ) _UpperCAmelCase = self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self._consolidate(_SCREAMING_SNAKE_CASE ) return column def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Mapping: """simple docstring""" _UpperCAmelCase = self.numpy_arrow_extractor().extract_batch(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.python_features_decoder.decode_batch(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.recursive_tensorize(_SCREAMING_SNAKE_CASE ) for column_name in batch: _UpperCAmelCase = self._consolidate(batch[column_name] ) return batch
329
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import PoolFormerImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=0.9 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> str: """simple docstring""" _UpperCAmelCase = size if size is not None else {'shortest_edge': 30} _UpperCAmelCase = crop_size if crop_size is not None else {'height': 30, 'width': 30} _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize_and_center_crop _UpperCAmelCase = size _UpperCAmelCase = crop_pct _UpperCAmelCase = crop_size _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> int: """simple docstring""" return { "size": self.size, "do_resize_and_center_crop": self.do_resize_and_center_crop, "crop_pct": self.crop_pct, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : Optional[Any] = PoolFormerImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = PoolFormerImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_resize_and_center_crop' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'size' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'crop_pct' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 30} ) self.assertEqual(image_processor.crop_size , {'height': 30, 'width': 30} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {'shortest_edge': 42} ) self.assertEqual(image_processor.crop_size , {'height': 84, 'width': 84} ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" pass def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) def UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , ) # Test batched _UpperCAmelCase = 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.crop_size['height'], self.image_processor_tester.crop_size['width'], ) , )
329
1
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" debug_launcher(test_script.main ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" debug_launcher(test_ops.main )
329
import unittest import numpy as np from transformers.testing_utils import is_flaky, 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 DonutImageProcessor class __a ( unittest.TestCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=7 , _SCREAMING_SNAKE_CASE=3 , _SCREAMING_SNAKE_CASE=18 , _SCREAMING_SNAKE_CASE=30 , _SCREAMING_SNAKE_CASE=400 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , _SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = parent _UpperCAmelCase = batch_size _UpperCAmelCase = num_channels _UpperCAmelCase = image_size _UpperCAmelCase = min_resolution _UpperCAmelCase = max_resolution _UpperCAmelCase = do_resize _UpperCAmelCase = size if size is not None else {'height': 18, 'width': 20} _UpperCAmelCase = do_thumbnail _UpperCAmelCase = do_align_axis _UpperCAmelCase = do_pad _UpperCAmelCase = do_normalize _UpperCAmelCase = image_mean _UpperCAmelCase = image_std def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __a ( UpperCAmelCase , unittest.TestCase ): _a : List[str] = DonutImageProcessor if is_vision_available() else None def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = DonutImageProcessingTester(self ) @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = 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 , 'do_thumbnail' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_align_long_axis' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_pad' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'do_normalize' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_mean' ) ) self.assertTrue(hasattr(_SCREAMING_SNAKE_CASE , 'image_std' ) ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'height': 18, 'width': 20} ) _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'height': 42, 'width': 42} ) # Previous config had dimensions in (width, height) order _UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {'height': 84, 'width': 42} ) def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" pass @is_flaky() def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> str: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , ) @is_flaky() def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _UpperCAmelCase = 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 _UpperCAmelCase = 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 _UpperCAmelCase = 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'], ) , )
329
1
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowerCAmelCase__ ( a__: dict ) -> tuple: '''simple docstring''' return (data["data"], data["target"]) def lowerCAmelCase__ ( a__: np.ndarray , a__: np.ndarray , a__: np.ndarray ) -> np.ndarray: '''simple docstring''' _UpperCAmelCase = XGBRegressor(verbosity=0 , random_state=4_2 ) xgb.fit(a__ , a__ ) # Predict target for test data _UpperCAmelCase = xgb.predict(a__ ) _UpperCAmelCase = predictions.reshape(len(a__ ) , 1 ) return predictions def lowerCAmelCase__ ( ) -> None: '''simple docstring''' _UpperCAmelCase = fetch_california_housing() _UpperCAmelCase , _UpperCAmelCase = data_handling(a__ ) _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = train_test_split( a__ , a__ , test_size=0.25 , random_state=1 ) _UpperCAmelCase = xgboost(a__ , a__ , a__ ) # Error printing print(F'''Mean Absolute Error : {mean_absolute_error(a__ , a__ )}''' ) print(F'''Mean Square Error : {mean_squared_error(a__ , a__ )}''' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
329
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase__ :Dict = logging.get_logger(__name__) lowerCAmelCase__ :Optional[int] = {'''openai-gpt''': '''https://huggingface.co/openai-gpt/resolve/main/config.json'''} class __a ( UpperCAmelCase ): _a : List[str] = 'openai-gpt' _a : int = { 'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , _SCREAMING_SNAKE_CASE=40478 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=768 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE=12 , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=1e-5 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE="cls_index" , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=0.1 , **_SCREAMING_SNAKE_CASE , ) -> str: """simple docstring""" _UpperCAmelCase = vocab_size _UpperCAmelCase = n_positions _UpperCAmelCase = n_embd _UpperCAmelCase = n_layer _UpperCAmelCase = n_head _UpperCAmelCase = afn _UpperCAmelCase = resid_pdrop _UpperCAmelCase = embd_pdrop _UpperCAmelCase = attn_pdrop _UpperCAmelCase = layer_norm_epsilon _UpperCAmelCase = initializer_range _UpperCAmelCase = summary_type _UpperCAmelCase = summary_use_proj _UpperCAmelCase = summary_activation _UpperCAmelCase = summary_first_dropout _UpperCAmelCase = summary_proj_to_labels super().__init__(**_SCREAMING_SNAKE_CASE )
329
1
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() lowerCAmelCase__ :List[Any] = logging.get_logger(__name__) def lowerCAmelCase__ ( a__: Optional[Any] , a__: Any , a__: Any ) -> int: '''simple docstring''' _UpperCAmelCase = UniSpeechSatForSequenceClassification.from_pretrained(a__ , config=a__ ) _UpperCAmelCase = downstream_dict['projector.weight'] _UpperCAmelCase = downstream_dict['projector.bias'] _UpperCAmelCase = downstream_dict['model.post_net.linear.weight'] _UpperCAmelCase = downstream_dict['model.post_net.linear.bias'] return model def lowerCAmelCase__ ( a__: str , a__: Tuple , a__: Dict ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = UniSpeechSatForAudioFrameClassification.from_pretrained(a__ , config=a__ ) _UpperCAmelCase = downstream_dict['model.linear.weight'] _UpperCAmelCase = downstream_dict['model.linear.bias'] return model def lowerCAmelCase__ ( a__: Any , a__: List[Any] , a__: List[str] ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = UniSpeechSatForXVector.from_pretrained(a__ , config=a__ ) _UpperCAmelCase = downstream_dict['connector.weight'] _UpperCAmelCase = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): _UpperCAmelCase = downstream_dict[ F'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] _UpperCAmelCase = downstream_dict[F'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] _UpperCAmelCase = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] _UpperCAmelCase = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] _UpperCAmelCase = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] _UpperCAmelCase = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] _UpperCAmelCase = downstream_dict['objective.W'] return model @torch.no_grad() def lowerCAmelCase__ ( a__: str , a__: Optional[Any] , a__: Tuple , a__: Any ) -> int: '''simple docstring''' _UpperCAmelCase = torch.load(a__ , map_location='cpu' ) _UpperCAmelCase = checkpoint['Downstream'] _UpperCAmelCase = UniSpeechSatConfig.from_pretrained(a__ ) _UpperCAmelCase = WavaVecaFeatureExtractor.from_pretrained( a__ , return_attention_mask=a__ , do_normalize=a__ ) _UpperCAmelCase = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): _UpperCAmelCase = convert_classification(a__ , a__ , a__ ) elif arch.endswith('ForAudioFrameClassification' ): _UpperCAmelCase = convert_diarization(a__ , a__ , a__ ) elif arch.endswith('ForXVector' ): _UpperCAmelCase = convert_xvector(a__ , a__ , a__ ) else: raise NotImplementedError(F'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: _UpperCAmelCase = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(a__ ) hf_model.save_pretrained(a__ ) if __name__ == "__main__": lowerCAmelCase__ :Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') lowerCAmelCase__ :str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
329
from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize('repo_id' , ['canonical_dataset_name', 'org-name/dataset-name'] ) @pytest.mark.parametrize('path' , ['filename.csv', 'filename with blanks.csv'] ) @pytest.mark.parametrize('revision' , [None, 'v2'] ) def lowerCAmelCase__ ( a__: Any , a__: Tuple , a__: Union[str, Any] ) -> Tuple: '''simple docstring''' _UpperCAmelCase = hf_hub_url(repo_id=a__ , path=a__ , revision=a__ ) assert url == F'''https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(a__ )}'''
329
1
from functools import lru_cache @lru_cache def lowerCAmelCase__ ( a__: int ) -> int: '''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()
329
from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers lowerCAmelCase__ :Optional[int] = [ '''python''', '''tqdm''', '''regex''', '''requests''', '''packaging''', '''filelock''', '''numpy''', '''tokenizers''', '''huggingface-hub''', '''safetensors''', '''accelerate''', '''pyyaml''', ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(f'''can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py''') def lowerCAmelCase__ ( a__: Tuple , a__: Optional[int]=None ) -> Any: '''simple docstring''' require_version(deps[pkg] , a__ )
329
1
import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class __a ( UpperCAmelCase , UpperCAmelCase , unittest.TestCase ): _a : List[Any] = IFPipeline _a : Union[str, Any] = TEXT_TO_IMAGE_PARAMS - {'width', 'height', 'latents'} _a : Any = TEXT_TO_IMAGE_BATCH_PARAMS _a : int = PipelineTesterMixin.required_optional_params - {'latents'} def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" return self._get_dummy_components() def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> Optional[int]: """simple docstring""" if str(_SCREAMING_SNAKE_CASE ).startswith('mps' ): _UpperCAmelCase = torch.manual_seed(_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = torch.Generator(device=_SCREAMING_SNAKE_CASE ).manual_seed(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != 'cuda' , reason='float16 requires CUDA' ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1e-1 ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1e-2 ) def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" self._test_save_load_local() def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1e-2 , ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @slow @require_torch_gpu class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self ) -> Union[str, Any]: """simple docstring""" _UpperCAmelCase = IFPipeline.from_pretrained('DeepFloyd/IF-I-XL-v1.0' , variant='fp16' , torch_dtype=torch.floataa ) _UpperCAmelCase = IFSuperResolutionPipeline.from_pretrained( 'DeepFloyd/IF-II-L-v1.0' , variant='fp16' , torch_dtype=torch.floataa , text_encoder=_SCREAMING_SNAKE_CASE , tokenizer=_SCREAMING_SNAKE_CASE ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to('cuda' ) _UpperCAmelCase , _UpperCAmelCase = pipe_a.encode_prompt('anime turtle' , device='cuda' ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _UpperCAmelCase = None _UpperCAmelCase = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _UpperCAmelCase = IFImgaImgPipeline(**pipe_a.components ) _UpperCAmelCase = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _UpperCAmelCase = IFInpaintingPipeline(**pipe_a.components ) _UpperCAmelCase = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _start_torch_memory_measurement() _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _start_torch_memory_measurement() _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , generator=_SCREAMING_SNAKE_CASE , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (64, 64, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # pipeline 2 _start_torch_memory_measurement() _UpperCAmelCase = torch.Generator(device='cpu' ).manual_seed(0 ) _UpperCAmelCase = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipe_a( prompt_embeds=_SCREAMING_SNAKE_CASE , negative_prompt_embeds=_SCREAMING_SNAKE_CASE , image=_SCREAMING_SNAKE_CASE , mask_image=_SCREAMING_SNAKE_CASE , original_image=_SCREAMING_SNAKE_CASE , generator=_SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='np' , ) _UpperCAmelCase = output.images[0] assert image.shape == (256, 256, 3) _UpperCAmelCase = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _UpperCAmelCase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy' ) assert_mean_pixel_difference(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def lowerCAmelCase__ ( ) -> int: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
329
from __future__ import annotations def lowerCAmelCase__ ( a__: dict , a__: str ) -> set[str]: '''simple docstring''' _UpperCAmelCase , _UpperCAmelCase = set(a__ ), [start] while stack: _UpperCAmelCase = stack.pop() explored.add(a__ ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(a__ ) return explored lowerCAmelCase__ :Tuple = { '''A''': ['''B''', '''C''', '''D'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F'''], '''D''': ['''B''', '''D'''], '''E''': ['''B''', '''F'''], '''F''': ['''C''', '''E''', '''G'''], '''G''': ['''F'''], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, '''A'''))
329
1
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 __a ( UpperCAmelCase ): _a : Any = (DPMSolverSDEScheduler,) _a : int = 10 def UpperCAmelCase__ ( self , **_SCREAMING_SNAKE_CASE ) -> str: """simple docstring""" _UpperCAmelCase = { 'num_train_timesteps': 1100, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**_SCREAMING_SNAKE_CASE ) return config def UpperCAmelCase__ ( self ) -> str: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Any: """simple docstring""" 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 UpperCAmelCase__ ( self ) -> List[Any]: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.scheduler_classes[0] _UpperCAmelCase = self.get_scheduler_config() _UpperCAmelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCAmelCase = self.dummy_model() _UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCAmelCase = sample.to(_SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): _UpperCAmelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = output.prev_sample _UpperCAmelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47821044921875 ) < 1e-2 assert abs(result_mean.item() - 0.2178705964565277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59352111816406 ) < 1e-2 assert abs(result_mean.item() - 0.22342906892299652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.scheduler_classes[0] _UpperCAmelCase = self.get_scheduler_config(prediction_type='v_prediction' ) _UpperCAmelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps ) _UpperCAmelCase = self.dummy_model() _UpperCAmelCase = self.dummy_sample_deter * scheduler.init_noise_sigma _UpperCAmelCase = sample.to(_SCREAMING_SNAKE_CASE ) for i, t in enumerate(scheduler.timesteps ): _UpperCAmelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = output.prev_sample _UpperCAmelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77149200439453 ) < 1e-2 assert abs(result_mean.item() - 0.16226289014816284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1663360595703 ) < 1e-2 assert abs(result_mean.item() - 0.16688326001167297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8487548828125 ) < 1e-2 assert abs(result_mean.item() - 0.1560530662536621 ) < 1e-3 def UpperCAmelCase__ ( self ) -> List[str]: """simple docstring""" _UpperCAmelCase = self.scheduler_classes[0] _UpperCAmelCase = self.get_scheduler_config() _UpperCAmelCase = scheduler_class(**_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.dummy_model() _UpperCAmelCase = self.dummy_sample_deter.to(_SCREAMING_SNAKE_CASE ) * scheduler.init_noise_sigma for t in scheduler.timesteps: _UpperCAmelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = output.prev_sample _UpperCAmelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46957397460938 ) < 1e-2 assert abs(result_mean.item() - 0.21805934607982635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59353637695312 ) < 1e-2 assert abs(result_mean.item() - 0.22342908382415771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52383422851562 ) < 1e-2 assert abs(result_mean.item() - 0.211619570851326 ) < 1e-3 def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = self.scheduler_classes[0] _UpperCAmelCase = self.get_scheduler_config() _UpperCAmelCase = scheduler_class(**_SCREAMING_SNAKE_CASE , use_karras_sigmas=_SCREAMING_SNAKE_CASE ) scheduler.set_timesteps(self.num_inference_steps , device=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = self.dummy_model() _UpperCAmelCase = self.dummy_sample_deter.to(_SCREAMING_SNAKE_CASE ) * scheduler.init_noise_sigma _UpperCAmelCase = sample.to(_SCREAMING_SNAKE_CASE ) for t in scheduler.timesteps: _UpperCAmelCase = scheduler.scale_model_input(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = model(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = scheduler.step(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = output.prev_sample _UpperCAmelCase = torch.sum(torch.abs(_SCREAMING_SNAKE_CASE ) ) _UpperCAmelCase = torch.mean(torch.abs(_SCREAMING_SNAKE_CASE ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66974135742188 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63653564453125 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3135223388672 ) < 1e-2 assert abs(result_mean.item() - 0.23003872730981811 ) < 1e-2
329
import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> int: """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights _UpperCAmelCase = FlaxDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = [t[-1] for t in os.walk(os.path.join(_SCREAMING_SNAKE_CASE , os.listdir(_SCREAMING_SNAKE_CASE )[0] , 'snapshots' ) )] _UpperCAmelCase = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith('.bin' ) for f in files ) @slow @require_flax class __a ( unittest.TestCase ): def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'hf-internal-testing/tiny-stable-diffusion-pipe' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 4 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.1514745 ) < 1e-3 assert np.abs(np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 49947.875 ) < 5e-1 _UpperCAmelCase = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(_SCREAMING_SNAKE_CASE ) == num_samples def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='flax' , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.05652401) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2383808.2) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Dict: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa ) _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.04003906) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2373516.75) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = FlaxDDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , set_alpha_to_one=_SCREAMING_SNAKE_CASE , steps_offset=1 , ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = scheduler.create_state() _UpperCAmelCase = scheduler_state _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.random.PRNGKey(0 ) _UpperCAmelCase = 50 _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) # shard inputs and rng _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.random.split(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.045043945) ) < 1e-3 assert np.abs((np.abs(_SCREAMING_SNAKE_CASE , dtype=np.floataa ).sum() - 2347693.5) ) < 5e-1 def UpperCAmelCase__ ( self ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = ( 'A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of' ' field, close up, split lighting, cinematic' ) _UpperCAmelCase = jax.device_count() _UpperCAmelCase = num_samples * [prompt] _UpperCAmelCase = jax.random.split(jax.random.PRNGKey(0 ) , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # With memory efficient attention _UpperCAmelCase , _UpperCAmelCase = FlaxStableDiffusionPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='bf16' , dtype=jnp.bfloataa , safety_checker=_SCREAMING_SNAKE_CASE , use_memory_efficient_attention=_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = replicate(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline.prepare_inputs(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = shard(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = pipeline(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , jit=_SCREAMING_SNAKE_CASE ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) _UpperCAmelCase = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1e-2
329
1
import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) lowerCAmelCase__ :Dict = pytest.mark.integration @pytest.mark.parametrize('path' , ['paws', 'csv'] ) def lowerCAmelCase__ ( a__: str , a__: Optional[int] ) -> Any: '''simple docstring''' inspect_dataset(a__ , a__ ) _UpperCAmelCase = path + '.py' assert script_name in os.listdir(a__ ) assert "__pycache__" not in os.listdir(a__ ) @pytest.mark.filterwarnings('ignore:inspect_metric is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.parametrize('path' , ['accuracy'] ) def lowerCAmelCase__ ( a__: Dict , a__: Tuple ) -> str: '''simple docstring''' inspect_metric(a__ , a__ ) _UpperCAmelCase = path + '.py' assert script_name in os.listdir(a__ ) assert "__pycache__" not in os.listdir(a__ ) @pytest.mark.parametrize( 'path, config_name, expected_splits' , [ ('squad', 'plain_text', ['train', 'validation']), ('dalle-mini/wit', 'dalle-mini--wit', ['train']), ('paws', 'labeled_final', ['train', 'test', 'validation']), ] , ) def lowerCAmelCase__ ( a__: Any , a__: str , a__: Tuple ) -> str: '''simple docstring''' _UpperCAmelCase = get_dataset_config_info(a__ , config_name=a__ ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( 'path, config_name, expected_exception' , [ ('paws', None, ValueError), ] , ) def lowerCAmelCase__ ( a__: Any , a__: Union[str, Any] , a__: int ) -> Optional[int]: '''simple docstring''' with pytest.raises(a__ ): get_dataset_config_info(a__ , config_name=a__ ) @pytest.mark.parametrize( 'path, expected' , [ ('squad', 'plain_text'), ('acronym_identification', 'default'), ('lhoestq/squad', 'plain_text'), ('lhoestq/test', 'default'), ('lhoestq/demo1', 'lhoestq--demo1'), ('dalle-mini/wit', 'dalle-mini--wit'), ] , ) def lowerCAmelCase__ ( a__: List[str] , a__: Tuple ) -> int: '''simple docstring''' _UpperCAmelCase = get_dataset_config_names(a__ ) assert expected in config_names @pytest.mark.parametrize( 'path, expected_configs, expected_splits_in_first_config' , [ ('squad', ['plain_text'], ['train', 'validation']), ('dalle-mini/wit', ['dalle-mini--wit'], ['train']), ('paws', ['labeled_final', 'labeled_swap', 'unlabeled_final'], ['train', 'test', 'validation']), ] , ) def lowerCAmelCase__ ( a__: str , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = get_dataset_infos(a__ ) assert list(infos.keys() ) == expected_configs _UpperCAmelCase = expected_configs[0] assert expected_config in infos _UpperCAmelCase = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( 'path, expected_config, expected_splits' , [ ('squad', 'plain_text', ['train', 'validation']), ('dalle-mini/wit', 'dalle-mini--wit', ['train']), ('paws', 'labeled_final', ['train', 'test', 'validation']), ] , ) def lowerCAmelCase__ ( a__: int , a__: Optional[int] , a__: str ) -> Dict: '''simple docstring''' _UpperCAmelCase = get_dataset_infos(a__ ) assert expected_config in infos _UpperCAmelCase = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( 'path, config_name, expected_exception' , [ ('paws', None, ValueError), ] , ) def lowerCAmelCase__ ( a__: List[str] , a__: List[Any] , a__: Tuple ) -> List[Any]: '''simple docstring''' with pytest.raises(a__ ): get_dataset_split_names(a__ , config_name=a__ )
329
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(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING lowerCAmelCase__ :int = logging.get_logger(__name__) @add_end_docstrings(UpperCAmelCase ) class __a ( UpperCAmelCase ): def __init__( self , *_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" super().__init__(*_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == 'tf' else MODEL_FOR_VISION_2_SEQ_MAPPING ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = {} _UpperCAmelCase = {} if prompt is not None: _UpperCAmelCase = prompt if generate_kwargs is not None: _UpperCAmelCase = generate_kwargs if max_new_tokens is not None: if "generate_kwargs" not in forward_kwargs: _UpperCAmelCase = {} if "max_new_tokens" in forward_kwargs["generate_kwargs"]: raise ValueError( '\'max_new_tokens\' is defined twice, once in \'generate_kwargs\' and once as a direct parameter,' ' please use only one' ) _UpperCAmelCase = max_new_tokens return preprocess_params, forward_kwargs, {} def __call__( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return super().__call__(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> int: """simple docstring""" _UpperCAmelCase = load_image(_SCREAMING_SNAKE_CASE ) if prompt is not None: if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): raise ValueError( f'''Received an invalid text input, got - {type(_SCREAMING_SNAKE_CASE )} - but expected a single string. ''' 'Note also that one single text can be provided for conditional image to text generation.' ) _UpperCAmelCase = self.model.config.model_type if model_type == "git": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(text=_SCREAMING_SNAKE_CASE , add_special_tokens=_SCREAMING_SNAKE_CASE ).input_ids _UpperCAmelCase = [self.tokenizer.cls_token_id] + input_ids _UpperCAmelCase = torch.tensor(_SCREAMING_SNAKE_CASE ).unsqueeze(0 ) model_inputs.update({'input_ids': input_ids} ) elif model_type == "pix2struct": _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , header_text=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) elif model_type != "vision-encoder-decoder": # vision-encoder-decoder does not support conditional generation _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) _UpperCAmelCase = self.tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) model_inputs.update(_SCREAMING_SNAKE_CASE ) else: raise ValueError(f'''Model type {model_type} does not support conditional text generation''' ) else: _UpperCAmelCase = self.image_processor(images=_SCREAMING_SNAKE_CASE , return_tensors=self.framework ) if self.model.config.model_type == "git" and prompt is None: _UpperCAmelCase = None return model_inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None ) -> List[str]: """simple docstring""" if ( "input_ids" in model_inputs and isinstance(model_inputs['input_ids'] , _SCREAMING_SNAKE_CASE ) and all(x is None for x in model_inputs['input_ids'] ) ): _UpperCAmelCase = None if generate_kwargs is None: _UpperCAmelCase = {} # FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py` # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name` # in the `_prepare_model_inputs` method. _UpperCAmelCase = model_inputs.pop(self.model.main_input_name ) _UpperCAmelCase = self.model.generate(_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) return model_outputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = [] for output_ids in model_outputs: _UpperCAmelCase = { 'generated_text': self.tokenizer.decode( _SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE , ) } records.append(_SCREAMING_SNAKE_CASE ) return records
329
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger lowerCAmelCase__ :Union[str, Any] = get_logger(__name__) lowerCAmelCase__ :List[str] = R''' Args: input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`): Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam search or log softmax for each vocabulary token when using beam search kwargs (`Dict[str, Any]`, *optional*): Additional logits processor specific kwargs. Return: `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores. ''' class __a : @add_start_docstrings(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class __a : @add_start_docstrings(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class __a ( UpperCAmelCase ): @add_start_docstrings(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" for processor in self: _UpperCAmelCase = inspect.signature(processor.__call__ ).parameters if len(_SCREAMING_SNAKE_CASE ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( f'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' f'''{processor.__class__} are passed to the logits processor.''' ) _UpperCAmelCase = processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) else: _UpperCAmelCase = processor(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or not (temperature > 0): raise ValueError(f'''`temperature` has to be a strictly positive float, but is {temperature}''' ) _UpperCAmelCase = temperature def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase = scores / self.temperature return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -float('Inf' ) , _SCREAMING_SNAKE_CASE = 1 ) -> str: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or (top_p < 0 or top_p > 1.0): raise ValueError(f'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or (min_tokens_to_keep < 1): raise ValueError(f'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) _UpperCAmelCase = top_p _UpperCAmelCase = filter_value _UpperCAmelCase = min_tokens_to_keep def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = lax.top_k(_SCREAMING_SNAKE_CASE , scores.shape[-1] ) _UpperCAmelCase = jnp.full_like(_SCREAMING_SNAKE_CASE , self.filter_value ) _UpperCAmelCase = jax.nn.softmax(_SCREAMING_SNAKE_CASE , axis=-1 ).cumsum(axis=-1 ) _UpperCAmelCase = cumulative_probs < self.top_p # include the token that is higher than top_p as well _UpperCAmelCase = jnp.roll(_SCREAMING_SNAKE_CASE , 1 ) score_mask |= score_mask.at[:, 0].set(_SCREAMING_SNAKE_CASE ) # min tokens to keep _UpperCAmelCase = score_mask.at[:, : self.min_tokens_to_keep].set(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.where(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jax.lax.sort_key_val(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )[-1] return next_scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -float('Inf' ) , _SCREAMING_SNAKE_CASE = 1 ) -> Optional[int]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or top_k <= 0: raise ValueError(f'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) _UpperCAmelCase = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = filter_value def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase = scores.shape _UpperCAmelCase = jnp.full(batch_size * vocab_size , self.filter_value ) _UpperCAmelCase = min(self.top_k , scores.shape[-1] ) # Safety check _UpperCAmelCase , _UpperCAmelCase = lax.top_k(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.broadcast_to((jnp.arange(_SCREAMING_SNAKE_CASE ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() _UpperCAmelCase = topk_scores.flatten() _UpperCAmelCase = topk_indices.flatten() + shift _UpperCAmelCase = next_scores_flat.at[topk_indices_flat].set(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = next_scores_flat.reshape(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return next_scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _UpperCAmelCase = bos_token_id def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase = jnp.full(scores.shape , -float('inf' ) ) _UpperCAmelCase = 1 - jnp.bool_(cur_len - 1 ) _UpperCAmelCase = jnp.where(_SCREAMING_SNAKE_CASE , new_scores.at[:, self.bos_token_id].set(0 ) , _SCREAMING_SNAKE_CASE ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = max_length _UpperCAmelCase = eos_token_id def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase = jnp.full(scores.shape , -float('inf' ) ) _UpperCAmelCase = 1 - jnp.bool_(cur_len - self.max_length + 1 ) _UpperCAmelCase = jnp.where(_SCREAMING_SNAKE_CASE , new_scores.at[:, self.eos_token_id].set(0 ) , _SCREAMING_SNAKE_CASE ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or min_length < 0: raise ValueError(f'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) or eos_token_id < 0: raise ValueError(f'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) _UpperCAmelCase = min_length _UpperCAmelCase = eos_token_id def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) _UpperCAmelCase = jnp.where(_SCREAMING_SNAKE_CASE , scores.at[:, self.eos_token_id].set(-float('inf' ) ) , _SCREAMING_SNAKE_CASE ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple: """simple docstring""" _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = begin_index def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = 1 - jnp.bool_(cur_len - self.begin_index ) _UpperCAmelCase = jnp.where(_SCREAMING_SNAKE_CASE , scores.at[:, self.begin_suppress_tokens].set(-float('inf' ) ) , _SCREAMING_SNAKE_CASE ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _UpperCAmelCase = list(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" _UpperCAmelCase = scores.at[..., self.suppress_tokens].set(-float('inf' ) ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]: """simple docstring""" _UpperCAmelCase = dict(_SCREAMING_SNAKE_CASE ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. _UpperCAmelCase = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: _UpperCAmelCase = force_token_array.at[index].set(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.intaa(_SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> jnp.ndarray: """simple docstring""" def _force_token(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = scores.shape[0] _UpperCAmelCase = self.force_token_array[generation_idx] _UpperCAmelCase = jnp.ones_like(_SCREAMING_SNAKE_CASE , dtype=scores.dtype ) * -float('inf' ) _UpperCAmelCase = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) _UpperCAmelCase = lax.dynamic_update_slice(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , (0, current_token) ) return new_scores _UpperCAmelCase = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(_SCREAMING_SNAKE_CASE ) , lambda: scores , ) , ) return scores class __a ( UpperCAmelCase ): def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" _UpperCAmelCase = generate_config.eos_token_id _UpperCAmelCase = generate_config.no_timestamps_token_id _UpperCAmelCase = generate_config.no_timestamps_token_id + 1 _UpperCAmelCase = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(_SCREAMING_SNAKE_CASE , 'max_initial_timestamp_index' ): _UpperCAmelCase = generate_config.max_initial_timestamp_index else: _UpperCAmelCase = model_config.vocab_size if self.max_initial_timestamp_index is None: _UpperCAmelCase = model_config.vocab_size def __call__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> int: """simple docstring""" _UpperCAmelCase = scores.at[:, self.no_timestamps_token_id].set(-float('inf' ) ) def handle_pairs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = jnp.where((cur_len - self.begin_index) >= 1 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , _SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = jnp.where((cur_len - self.begin_index) < 2 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , ) return jnp.where( _SCREAMING_SNAKE_CASE , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf' ) ) , scores_k.at[: self.eos_token_id].set(-float('inf' ) ) , ) , _SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = jax.vmap(_SCREAMING_SNAKE_CASE )(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.where(cur_len == self.begin_index , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) _UpperCAmelCase = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , _SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = self.timestamp_begin + self.max_initial_timestamp_index _UpperCAmelCase = jnp.where( _SCREAMING_SNAKE_CASE , scores.at[:, last_allowed + 1 :].set(-float('inf' ) ) , _SCREAMING_SNAKE_CASE , ) # if sum of probability over timestamps is above any other token, sample timestamp _UpperCAmelCase = jax.nn.log_softmax(_SCREAMING_SNAKE_CASE , axis=-1 ) def handle_cumulative_probs(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): _UpperCAmelCase = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) _UpperCAmelCase = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf' ) ) , _SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = jax.vmap(_SCREAMING_SNAKE_CASE )(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) return scores
329
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def lowerCAmelCase__ ( *a__: str , a__: Optional[Union[Dict, Any]] = None , a__: Dict=True , a__: Any=2 ) -> Union[str, Any]: '''simple docstring''' from .. import __version__ _UpperCAmelCase = take_from _UpperCAmelCase = () if not isinstance(args[0] , a__ ): _UpperCAmelCase = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a__ ).base_version ) >= version.parse(a__ ): raise ValueError( F'''The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'''' F''' version {__version__} is >= {version_name}''' ) _UpperCAmelCase = None if isinstance(a__ , a__ ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a__ ),) _UpperCAmelCase = F'''The `{attribute}` argument is deprecated and will be removed in version {version_name}.''' elif hasattr(a__ , a__ ): values += (getattr(a__ , a__ ),) _UpperCAmelCase = F'''The `{attribute}` attribute is deprecated and will be removed in version {version_name}.''' elif deprecated_kwargs is None: _UpperCAmelCase = F'''`{attribute}` is deprecated and will be removed in version {version_name}.''' if warning is not None: _UpperCAmelCase = warning + ' ' if standard_warn else '' warnings.warn(warning + message , a__ , stacklevel=a__ ) if isinstance(a__ , a__ ) and len(a__ ) > 0: _UpperCAmelCase = inspect.getouterframes(inspect.currentframe() )[1] _UpperCAmelCase = call_frame.filename _UpperCAmelCase = call_frame.lineno _UpperCAmelCase = call_frame.function _UpperCAmelCase , _UpperCAmelCase = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'''{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`''' ) if len(a__ ) == 0: return elif len(a__ ) == 1: return values[0] return values
329
1
import os 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 lowerCAmelCase__ :Tuple = logging.get_logger(__name__) lowerCAmelCase__ :str = '''▁''' lowerCAmelCase__ :int = {'''vocab_file''': '''sentencepiece.bpe.model''', '''monolingual_vocab_file''': '''dict.txt'''} lowerCAmelCase__ :int = { '''vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model''', }, '''monolingual_vocab_file''': { '''vinai/bartpho-syllable''': '''https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt''', }, } lowerCAmelCase__ :int = {'''vinai/bartpho-syllable''': 1_0_2_4} class __a ( UpperCAmelCase ): _a : List[str] = VOCAB_FILES_NAMES _a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP _a : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a : Union[str, Any] = ['input_ids', 'attention_mask'] def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , ) -> None: """simple docstring""" _UpperCAmelCase = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token _UpperCAmelCase = {} 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 , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , sp_model_kwargs=self.sp_model_kwargs , **_SCREAMING_SNAKE_CASE , ) _UpperCAmelCase = vocab_file _UpperCAmelCase = monolingual_vocab_file _UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_SCREAMING_SNAKE_CASE ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility _UpperCAmelCase = {} _UpperCAmelCase = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_SCREAMING_SNAKE_CASE ) not in self.fairseq_tokens_to_ids: _UpperCAmelCase = cnt cnt += 1 with open(_SCREAMING_SNAKE_CASE , 'r' , encoding='utf-8' ) as f: for line in f.readlines(): _UpperCAmelCase = line.strip().split()[0] _UpperCAmelCase = len(self.fairseq_tokens_to_ids ) if str(_SCREAMING_SNAKE_CASE ) not in self.fairseq_tokens_to_ids: _UpperCAmelCase = len(self.fairseq_tokens_to_ids ) _UpperCAmelCase = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Tuple: """simple docstring""" _UpperCAmelCase = self.__dict__.copy() _UpperCAmelCase = None _UpperCAmelCase = self.sp_model.serialized_model_proto() return state def __setstate__( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): _UpperCAmelCase = {} _UpperCAmelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] _UpperCAmelCase = [self.cls_token_id] _UpperCAmelCase = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False ) -> List[int]: """simple docstring""" 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, 1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1] def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]: """simple docstring""" _UpperCAmelCase = [self.sep_token_id] _UpperCAmelCase = [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] @property def UpperCAmelCase__ ( self ) -> Optional[Any]: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def UpperCAmelCase__ ( self ) -> int: """simple docstring""" _UpperCAmelCase = {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 UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" return self.sp_model.encode(_SCREAMING_SNAKE_CASE , out_type=_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return self.fairseq_ids_to_tokens[index] def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" _UpperCAmelCase = ''.join(_SCREAMING_SNAKE_CASE ).replace(_SCREAMING_SNAKE_CASE , ' ' ).strip() return out_string def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_SCREAMING_SNAKE_CASE ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return _UpperCAmelCase = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) _UpperCAmelCase = os.path.join( _SCREAMING_SNAKE_CASE , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_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: _UpperCAmelCase = self.sp_model.serialized_model_proto() fi.write(_SCREAMING_SNAKE_CASE ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _SCREAMING_SNAKE_CASE ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , _SCREAMING_SNAKE_CASE ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_SCREAMING_SNAKE_CASE , 'w' , encoding='utf-8' ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'''{str(_SCREAMING_SNAKE_CASE )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
329
import math lowerCAmelCase__ :Optional[int] = 1_0 lowerCAmelCase__ :Optional[Any] = 7 lowerCAmelCase__ :Union[str, Any] = BALLS_PER_COLOUR * NUM_COLOURS def lowerCAmelCase__ ( a__: int = 2_0 ) -> str: '''simple docstring''' _UpperCAmelCase = math.comb(a__ , a__ ) _UpperCAmelCase = math.comb(NUM_BALLS - BALLS_PER_COLOUR , a__ ) _UpperCAmelCase = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(2_0))
329
1
from pathlib import Path import fire def lowerCAmelCase__ ( a__: str , a__: str , a__: int ) -> List[str]: '''simple docstring''' _UpperCAmelCase = Path(a__ ) _UpperCAmelCase = Path(a__ ) dest_dir.mkdir(exist_ok=a__ ) for path in src_dir.iterdir(): _UpperCAmelCase = [x.rstrip() for x in list(path.open().readlines() )][:n] _UpperCAmelCase = dest_dir.joinpath(path.name ) print(a__ ) dest_path.open('w' ).write('\n'.join(a__ ) ) if __name__ == "__main__": fire.Fire(minify)
329
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ :str = { '''configuration_megatron_bert''': ['''MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MegatronBertConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ :Union[str, Any] = [ '''MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MegatronBertForCausalLM''', '''MegatronBertForMaskedLM''', '''MegatronBertForMultipleChoice''', '''MegatronBertForNextSentencePrediction''', '''MegatronBertForPreTraining''', '''MegatronBertForQuestionAnswering''', '''MegatronBertForSequenceClassification''', '''MegatronBertForTokenClassification''', '''MegatronBertModel''', '''MegatronBertPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys lowerCAmelCase__ :List[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
329
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class __a ( UpperCAmelCase ): _a : List[str] = 'char' _a : Union[str, Any] = 'bpe' _a : Dict = 'wp' lowerCAmelCase__ :Optional[Any] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __a ( UpperCAmelCase ): _a : Any = ['image_processor', 'char_tokenizer'] _a : Union[str, Any] = 'ViTImageProcessor' _a : Union[str, Any] = 'MgpstrTokenizer' def __init__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = 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 , ) _UpperCAmelCase = kwargs.pop('feature_extractor' ) _UpperCAmelCase = 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`.' ) _UpperCAmelCase = tokenizer _UpperCAmelCase = AutoTokenizer.from_pretrained('gpt2' ) _UpperCAmelCase = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) def __call__( self , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None , **_SCREAMING_SNAKE_CASE ) -> List[Any]: """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: _UpperCAmelCase = self.image_processor(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if text is not None: _UpperCAmelCase = 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: _UpperCAmelCase = encodings['input_ids'] return inputs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = sequences _UpperCAmelCase = char_preds.size(0 ) _UpperCAmelCase , _UpperCAmelCase = self._decode_helper(_SCREAMING_SNAKE_CASE , 'char' ) _UpperCAmelCase , _UpperCAmelCase = self._decode_helper(_SCREAMING_SNAKE_CASE , 'bpe' ) _UpperCAmelCase , _UpperCAmelCase = self._decode_helper(_SCREAMING_SNAKE_CASE , 'wp' ) _UpperCAmelCase = [] _UpperCAmelCase = [] for i in range(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = [char_scores[i], bpe_scores[i], wp_scores[i]] _UpperCAmelCase = [char_strs[i], bpe_strs[i], wp_strs[i]] _UpperCAmelCase = scores.index(max(_SCREAMING_SNAKE_CASE ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) _UpperCAmelCase = {} _UpperCAmelCase = final_strs _UpperCAmelCase = final_scores _UpperCAmelCase = char_strs _UpperCAmelCase = bpe_strs _UpperCAmelCase = wp_strs return out def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" if format == DecodeType.CHARACTER: _UpperCAmelCase = self.char_decode _UpperCAmelCase = 1 _UpperCAmelCase = '[s]' elif format == DecodeType.BPE: _UpperCAmelCase = self.bpe_decode _UpperCAmelCase = 2 _UpperCAmelCase = '#' elif format == DecodeType.WORDPIECE: _UpperCAmelCase = self.wp_decode _UpperCAmelCase = 102 _UpperCAmelCase = '[SEP]' else: raise ValueError(f'''Format {format} is not supported.''' ) _UpperCAmelCase , _UpperCAmelCase = [], [] _UpperCAmelCase = pred_logits.size(0 ) _UpperCAmelCase = pred_logits.size(1 ) _UpperCAmelCase , _UpperCAmelCase = pred_logits.topk(1 , dim=-1 , largest=_SCREAMING_SNAKE_CASE , sorted=_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = preds_index.view(-1 , _SCREAMING_SNAKE_CASE )[:, 1:] _UpperCAmelCase = decoder(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase , _UpperCAmelCase = torch.nn.functional.softmax(_SCREAMING_SNAKE_CASE , dim=2 ).max(dim=2 ) _UpperCAmelCase = preds_max_prob[:, 1:] for index in range(_SCREAMING_SNAKE_CASE ): _UpperCAmelCase = preds_str[index].find(_SCREAMING_SNAKE_CASE ) _UpperCAmelCase = preds_str[index][:pred_eos] _UpperCAmelCase = preds_index[index].cpu().tolist() _UpperCAmelCase = pred_index.index(_SCREAMING_SNAKE_CASE ) if eos_token in pred_index else -1 _UpperCAmelCase = preds_max_prob[index][: pred_eos_index + 1] _UpperCAmelCase = 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 , _SCREAMING_SNAKE_CASE ) -> List[str]: """simple docstring""" _UpperCAmelCase = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(_SCREAMING_SNAKE_CASE )] return decode_strs def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: """simple docstring""" return self.bpe_tokenizer.batch_decode(_SCREAMING_SNAKE_CASE ) def UpperCAmelCase__ ( self , _SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" _UpperCAmelCase = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(_SCREAMING_SNAKE_CASE )] return decode_strs
329
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def lowerCAmelCase__ ( a__: Tuple , a__: Optional[Any] , a__: Any ) -> List[Any]: '''simple docstring''' _UpperCAmelCase = AutoConfig.from_pretrained(a__ ) _UpperCAmelCase = FlaxAutoModelForSeqaSeqLM.from_config(config=a__ ) _UpperCAmelCase = checkpoints.load_tax_checkpoint(a__ ) _UpperCAmelCase = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": _UpperCAmelCase = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": _UpperCAmelCase = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['encoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_global_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = tax_mlp_layer_norm _UpperCAmelCase = flax_model_encoder_layer_block # Only for layer 0: _UpperCAmelCase = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": _UpperCAmelCase = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_encoder_global_rel_embedding # Assigning _UpperCAmelCase = tax_model['target']['encoder']['encoder_norm']['scale'] _UpperCAmelCase = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): _UpperCAmelCase = F'''layers_{str(a__ )}''' # Self-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] _UpperCAmelCase = tax_enc_dec_attention_module['key']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['out']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['query']['kernel'] _UpperCAmelCase = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization _UpperCAmelCase = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning _UpperCAmelCase = flax_model.params['decoder']['block'][str(a__ )]['layer'] _UpperCAmelCase = tax_attention_key _UpperCAmelCase = tax_attention_out _UpperCAmelCase = tax_attention_query _UpperCAmelCase = tax_attention_value _UpperCAmelCase = tax_pre_attention_layer_norm _UpperCAmelCase = tax_enc_dec_attention_key _UpperCAmelCase = tax_enc_dec_attention_out _UpperCAmelCase = tax_enc_dec_attention_query _UpperCAmelCase = tax_enc_dec_attention_value _UpperCAmelCase = tax_cross_layer_norm if split_mlp_wi: _UpperCAmelCase = tax_mlp_wi_a _UpperCAmelCase = tax_mlp_wi_a else: _UpperCAmelCase = tax_mlp_wi _UpperCAmelCase = tax_mlp_wo _UpperCAmelCase = txa_mlp_layer_norm _UpperCAmelCase = flax_model_decoder_layer_block # Decoder Normalization _UpperCAmelCase = tax_model['target']['decoder']['decoder_norm']['scale'] _UpperCAmelCase = txa_decoder_norm # Only for layer 0: _UpperCAmelCase = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T _UpperCAmelCase = tax_decoder_rel_embedding # Token Embeddings _UpperCAmelCase = tax_model['target']['token_embedder']['embedding'] _UpperCAmelCase = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: _UpperCAmelCase = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(a__ ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": lowerCAmelCase__ :List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path the T5X checkpoint.''' ) parser.add_argument('''--config_name''', default=None, type=str, required=True, help='''Config name of LongT5/T5 model.''') parser.add_argument( '''--flax_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output FLAX model.''' ) lowerCAmelCase__ :List[str] = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
329
1