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
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase lowerCAmelCase = logging.get_logger(__name__) lowerCAmelCase = { 'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json', 'allenai/longformer-large-4096': 'https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json', 'allenai/longformer-large-4096-finetuned-triviaqa': ( 'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json' ), 'allenai/longformer-base-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json' ), 'allenai/longformer-large-4096-extra.pos.embd.only': ( 'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json' ), } class A ( A__ ): UpperCamelCase_ : Union[str, Any] ='''longformer''' def __init__(self , lowerCAmelCase = 5_1_2 , lowerCAmelCase = 2 , lowerCAmelCase = 1 , lowerCAmelCase = 0 , lowerCAmelCase = 2 , lowerCAmelCase = 3_0_5_2_2 , lowerCAmelCase = 7_6_8 , lowerCAmelCase = 1_2 , lowerCAmelCase = 1_2 , lowerCAmelCase = 3_0_7_2 , lowerCAmelCase = "gelu" , lowerCAmelCase = 0.1 , lowerCAmelCase = 0.1 , lowerCAmelCase = 5_1_2 , lowerCAmelCase = 2 , lowerCAmelCase = 0.02 , lowerCAmelCase = 1E-12 , lowerCAmelCase = False , **lowerCAmelCase , ): super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) __lowercase= attention_window __lowercase= sep_token_id __lowercase= bos_token_id __lowercase= eos_token_id __lowercase= vocab_size __lowercase= hidden_size __lowercase= num_hidden_layers __lowercase= num_attention_heads __lowercase= hidden_act __lowercase= intermediate_size __lowercase= hidden_dropout_prob __lowercase= attention_probs_dropout_prob __lowercase= max_position_embeddings __lowercase= type_vocab_size __lowercase= initializer_range __lowercase= layer_norm_eps __lowercase= onnx_export class A ( A__ ): def __init__(self , lowerCAmelCase , lowerCAmelCase = "default" , lowerCAmelCase = None ): super().__init__(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) __lowercase= True @property def _A (self ): if self.task == "multiple-choice": __lowercase= {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowercase= {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('global_attention_mask', dynamic_axis), ] ) @property def _A (self ): __lowercase= super().outputs if self.task == "default": __lowercase= {0: 'batch'} return outputs @property def _A (self ): return 1E-4 @property def _A (self ): # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 1_4 ) def _A (self , lowerCAmelCase , lowerCAmelCase = -1 , lowerCAmelCase = -1 , lowerCAmelCase = False , lowerCAmelCase = None , ): __lowercase= super().generate_dummy_inputs( preprocessor=_lowerCAmelCase , batch_size=_lowerCAmelCase , seq_length=_lowerCAmelCase , is_pair=_lowerCAmelCase , framework=_lowerCAmelCase ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly __lowercase= torch.zeros_like(inputs['input_ids'] ) # make every second token global __lowercase= 1 return inputs
295
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCAmelCase : '''simple docstring''' def __init__(self : Tuple , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=13 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : Dict=2 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Dict=16 , _lowerCAmelCase : str=[1, 2, 1] , _lowerCAmelCase : List[Any]=[2, 2, 4] , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Any=2.0 , _lowerCAmelCase : Any=True , _lowerCAmelCase : int=0.0 , _lowerCAmelCase : List[Any]=0.0 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : List[str]="gelu" , _lowerCAmelCase : Optional[Any]=False , _lowerCAmelCase : str=True , _lowerCAmelCase : List[str]=0.02 , _lowerCAmelCase : Dict=1e-5 , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=None , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=10 , _lowerCAmelCase : int=8 , ): A = parent A = batch_size A = image_size A = patch_size A = num_channels A = embed_dim A = depths A = num_heads A = window_size A = mlp_ratio A = qkv_bias A = hidden_dropout_prob A = attention_probs_dropout_prob A = drop_path_rate A = hidden_act A = use_absolute_embeddings A = patch_norm A = layer_norm_eps A = initializer_range A = is_training A = scope A = use_labels A = type_sequence_label_size A = encoder_stride def A (self : Dict ): A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A = None if self.use_labels: A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A = self.get_config() return config, pixel_values, labels def A (self : Optional[Any] ): return SwinvaConfig( 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 , ) def A (self : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] ): A = SwinvaModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) A = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A = 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 A (self : Tuple , _lowerCAmelCase : Dict , _lowerCAmelCase : int , _lowerCAmelCase : Optional[int] ): A = SwinvaForMaskedImageModeling(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A = 1 A = SwinvaForMaskedImageModeling(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def A (self : List[str] , _lowerCAmelCase : Any , _lowerCAmelCase : Dict , _lowerCAmelCase : Any ): A = self.type_sequence_label_size A = SwinvaForImageClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A (self : Union[str, Any] ): A = self.prepare_config_and_inputs() A , A , A = config_and_inputs A = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __lowerCAmelCase = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def A (self : Any ): A = SwinvaModelTester(self ) A = ConfigTester(self , config_class=_lowerCAmelCase , embed_dim=37 ) def A (self : Dict ): 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 A (self : int ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def A (self : Dict ): pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def A (self : Optional[int] ): pass def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) ) def A (self : Optional[int] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A = [*signature.parameters.keys()] A = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def A (self : int ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = True for model_class in self.all_model_classes: A = True A = False A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions A = len(self.model_tester.depths ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] A = True A = config.window_size**2 A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) A = len(_lowerCAmelCase ) # Check attention is always last and order is fine A = True A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): A = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A = 2 self.assertEqual(out_len + added_hidden_states , len(_lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def A (self : List[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] ): A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.hidden_states A = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # Swinv2 has a different seq_length A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = (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] , ) A = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) A , A , A , A = reshaped_hidden_states[0].shape A = ( reshaped_hidden_states[0].view(_lowerCAmelCase , _lowerCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A (self : Tuple ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ( 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: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = ( 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) ) A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) def A (self : Optional[int] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase ) def A (self : Union[str, Any] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def A (self : Optional[Any] ): for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = SwinvaModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def A (self : Optional[Any] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = _config_zero_init(_lowerCAmelCase ) for model_class in self.all_model_classes: A = model_class(config=_lowerCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def A (self : List[str] ): return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def A (self : List[str] ): A = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( _lowerCAmelCase ) A = self.default_image_processor A = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) A = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): A = model(**_lowerCAmelCase ) # verify the logits A = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) A = torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 ) )
258
0
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def a__ ( __UpperCamelCase ): # picklable for multiprocessing return x.sum() def a__ ( __UpperCamelCase ): # picklable for multiprocessing return i + 1 @dataclass class lowerCamelCase : """simple docstring""" lowerCamelCase__ = 4_2 lowerCamelCase__ = 4_2 class lowerCamelCase (A__ ): """simple docstring""" def __A ( self : Tuple ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 1 SCREAMING_SNAKE_CASE_ = [1, 2] SCREAMING_SNAKE_CASE_ = {"a": 1, "b": 2} SCREAMING_SNAKE_CASE_ = {"a": [1, 2], "b": [3, 4]} SCREAMING_SNAKE_CASE_ = {"a": {"1": 1}, "b": 2} SCREAMING_SNAKE_CASE_ = {"a": 1, "b": 2, "c": 3, "d": 4} SCREAMING_SNAKE_CASE_ = {} SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = 2 SCREAMING_SNAKE_CASE_ = [2, 3] SCREAMING_SNAKE_CASE_ = {"a": 2, "b": 3} SCREAMING_SNAKE_CASE_ = {"a": [2, 3], "b": [4, 5]} SCREAMING_SNAKE_CASE_ = {"a": {"1": 2}, "b": 3} SCREAMING_SNAKE_CASE_ = {"a": 2, "b": 3, "c": 4, "d": 5} self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = 2 self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = {"a": np.eye(2 ), "b": np.zeros(3 ), "c": np.ones(2 )} SCREAMING_SNAKE_CASE_ = {"a": 2, "b": 0, "c": 2} SCREAMING_SNAKE_CASE_ = { "a": np.eye(2 ).astype(_lowerCAmelCase ), "b": np.zeros(3 ).astype(_lowerCAmelCase ), "c": np.ones(2 ).astype(_lowerCAmelCase ), } self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(_lowerCAmelCase ): # can't pickle a local lambda map_nested(lambda __magic_name__ : x + 1 , _lowerCAmelCase , num_proc=_lowerCAmelCase ) def __A ( self : List[Any] ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = {"a": 1, "b": 2} SCREAMING_SNAKE_CASE_ = {"a": 3, "b": 4} SCREAMING_SNAKE_CASE_ = {"a": 5, "b": 6} SCREAMING_SNAKE_CASE_ = sorted([("a", (1, 3, 5)), ("b", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ) , _lowerCAmelCase ) def __A ( self : Union[str, Any] ) -> Tuple: class lowerCamelCase : """simple docstring""" lowerCamelCase__ = '''bar''' SCREAMING_SNAKE_CASE_ = Foo() self.assertEqual(foo.my_attr , "bar" ) with temporary_assignment(_lowerCAmelCase , "my_attr" , "BAR" ): self.assertEqual(foo.my_attr , "BAR" ) self.assertEqual(foo.my_attr , "bar" ) @pytest.mark.parametrize( "iterable_length, num_proc, expected_num_proc" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (1_6, 1_6, 1_6), (1_6, 1_7, 1_6), (1_7, 1_6, 1_6), ] , ) def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): with patch("datasets.utils.py_utils._single_map_nested" ) as mock_single_map_nested, patch( "datasets.parallel.parallel.Pool" ) as mock_multiprocessing_pool: SCREAMING_SNAKE_CASE_ = {F'''{i}''': i for i in range(__UpperCamelCase )} SCREAMING_SNAKE_CASE_ = map_nested(lambda __UpperCamelCase : x + 1_0 , __UpperCamelCase , num_proc=__UpperCamelCase , parallel_min_length=1_6 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class lowerCamelCase (A__ ): """simple docstring""" @require_tf def __A ( self : Dict ) -> Optional[Any]: import tensorflow as tf from tensorflow.keras import layers SCREAMING_SNAKE_CASE_ = layers.Dense(2 ) def gen_random_output(): SCREAMING_SNAKE_CASE_ = tf.random.uniform((1, 3) ) return model(_lowerCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def __A ( self : Tuple ) -> Optional[Any]: import torch def gen_random_output(): SCREAMING_SNAKE_CASE_ = torch.nn.Linear(3 , 2 ) SCREAMING_SNAKE_CASE_ = torch.rand(1 , 3 ) return model(_lowerCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def __A ( self : str ) -> Union[str, Any]: def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() with temp_seed(42 ): SCREAMING_SNAKE_CASE_ = gen_random_output() SCREAMING_SNAKE_CASE_ = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("input_data" , [{}] ) def a__ ( __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__UpperCamelCase ).data assert output_data == input_data @pytest.mark.parametrize( "data, expected_output" , [ ({}, []), ([], []), ("foo", ["foo"]), (["foo", "bar"], ["foo", "bar"]), ([["foo", "bar"]], ["foo", "bar"]), ([[["foo"], ["bar"]]], ["foo", "bar"]), ([[["foo"], "bar"]], ["foo", "bar"]), ({"a": 1, "b": 2}, [1, 2]), ({"a": [1, 2], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[1, 2]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[[3], [4]]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [[3, 4]]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, 4]}, [1, 2, 3, 4]), ({"a": [[[1], [2]]], "b": [3, [4]]}, [1, 2, 3, 4]), ({"a": {"1": 1}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": 2}, [1, 2]), ({"a": {"1": [1]}, "b": [2]}, [1, 2]), ] , ) def a__ ( __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = NestedDataStructure(__UpperCamelCase ).flatten() assert output == expected_output def a__ ( ): SCREAMING_SNAKE_CASE_ = A(x=1 , y="foobar" ) SCREAMING_SNAKE_CASE_ = {"x": 1, "y": "foobar"} assert asdict(__UpperCamelCase ) == expected_output SCREAMING_SNAKE_CASE_ = {"a": {"b": A(x=1_0 , y="foo" )}, "c": [A(x=2_0 , y="bar" )]} SCREAMING_SNAKE_CASE_ = {"a": {"b": {"x": 1_0, "y": "foo"}}, "c": [{"x": 2_0, "y": "bar"}]} assert asdict(__UpperCamelCase ) == expected_output with pytest.raises(__UpperCamelCase ): asdict([1, A(x=1_0 , y="foo" )] ) def a__ ( __UpperCamelCase ): return text.split() def a__ ( __UpperCamelCase ): yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def a__ ( ): with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__UpperCamelCase , _split_text , kwargs_iterable=[{"text": "hello there"}] * 1_0 ) ) assert out.count("hello" ) == 1_0 assert out.count("there" ) == 1_0 assert len(__UpperCamelCase ) == 2_0 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = list(iflatmap_unordered(__UpperCamelCase , _split_text , kwargs_iterable=[{"text": "hello there"}] * 1_0 ) ) assert out.count("hello" ) == 1_0 assert out.count("there" ) == 1_0 assert len(__UpperCamelCase ) == 2_0 # check that we get items as fast as possible with Pool(2 ) as pool: SCREAMING_SNAKE_CASE_ = [] for yield_time, content in iflatmap_unordered( __UpperCamelCase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"content": "a"}, {"content": "b"}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__UpperCamelCase ) assert out.count("a" ) == 2 assert out.count("b" ) == 2 assert len(__UpperCamelCase ) == 4
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" def get_matched_characters(UpperCAmelCase , UpperCAmelCase ) -> str: A = [] A = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): A = int(max(0 , i - limit ) ) A = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(UpperCAmelCase ) A = f"""{_stra[0:_stra.index(UpperCAmelCase )]} {_stra[_stra.index(UpperCAmelCase ) + 1:]}""" return "".join(UpperCAmelCase ) # matching characters A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = len(UpperCAmelCase ) # transposition A = ( len([(ca, ca) for ca, ca in zip(UpperCAmelCase , UpperCAmelCase ) if ca != ca] ) // 2 ) if not match_count: A = 0.0 else: A = ( 1 / 3 * ( match_count / len(UpperCAmelCase ) + match_count / len(UpperCAmelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
258
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
180
'''simple docstring''' import datasets from .evaluate import evaluate _lowerCamelCase : List[str] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' _lowerCamelCase : List[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' _lowerCamelCase : Dict = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def A (self : int ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def A (self : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ): A = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} A = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] A = evaluate(dataset=_lowerCAmelCase , predictions=_lowerCAmelCase ) return score
258
0
'''simple docstring''' from collections.abc import Callable class lowercase_ : def __init__( self , a = None ): # Stores actual heap items. UpperCamelCase__ = [] # Stores indexes of each item for supporting updates and deletion. UpperCamelCase__ = {} # Stores current size of heap. UpperCamelCase__ = 0 # Stores function used to evaluate the score of an item on which basis ordering # will be done. UpperCamelCase__ = key or (lambda a : x) def __a ( self , a ): return int((i - 1) / 2 ) if i > 0 else None def __a ( self , a ): UpperCamelCase__ = int(2 * i + 1 ) return left if 0 < left < self.size else None def __a ( self , a ): UpperCamelCase__ = int(2 * i + 2 ) return right if 0 < right < self.size else None def __a ( self , a , a ): UpperCamelCase__ , UpperCamelCase__ = ( self.pos_map[self.arr[j][0]], self.pos_map[self.arr[i][0]], ) # Then swap the items in the list. UpperCamelCase__ , UpperCamelCase__ = self.arr[j], self.arr[i] def __a ( self , a , a ): return self.arr[i][1] < self.arr[j][1] def __a ( self , a ): UpperCamelCase__ = self._left(_lowerCAmelCase ) UpperCamelCase__ = self._right(_lowerCAmelCase ) UpperCamelCase__ = i if left is not None and not self._cmp(_lowerCAmelCase , _lowerCAmelCase ): UpperCamelCase__ = left if right is not None and not self._cmp(_lowerCAmelCase , _lowerCAmelCase ): UpperCamelCase__ = right return valid_parent def __a ( self , a ): UpperCamelCase__ = self._parent(_lowerCAmelCase ) while parent is not None and not self._cmp(_lowerCAmelCase , _lowerCAmelCase ): self._swap(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ , UpperCamelCase__ = parent, self._parent(_lowerCAmelCase ) def __a ( self , a ): UpperCamelCase__ = self._get_valid_parent(_lowerCAmelCase ) while valid_parent != index: self._swap(_lowerCAmelCase , _lowerCAmelCase ) UpperCamelCase__ , UpperCamelCase__ = valid_parent, self._get_valid_parent(_lowerCAmelCase ) def __a ( self , a , a ): if item not in self.pos_map: return UpperCamelCase__ = self.pos_map[item] UpperCamelCase__ = [item, self.key(_lowerCAmelCase )] # Make sure heap is right in both up and down direction. # Ideally only one of them will make any change. self._heapify_up(_lowerCAmelCase ) self._heapify_down(_lowerCAmelCase ) def __a ( self , a ): if item not in self.pos_map: return UpperCamelCase__ = self.pos_map[item] del self.pos_map[item] UpperCamelCase__ = self.arr[self.size - 1] UpperCamelCase__ = index self.size -= 1 # Make sure heap is right in both up and down direction. Ideally only one # of them will make any change- so no performance loss in calling both. if self.size > index: self._heapify_up(_lowerCAmelCase ) self._heapify_down(_lowerCAmelCase ) def __a ( self , a , a ): UpperCamelCase__ = len(self.arr ) if arr_len == self.size: self.arr.append([item, self.key(_lowerCAmelCase )] ) else: UpperCamelCase__ = [item, self.key(_lowerCAmelCase )] UpperCamelCase__ = self.size self.size += 1 self._heapify_up(self.size - 1 ) def __a ( self ): return self.arr[0] if self.size else None def __a ( self ): UpperCamelCase__ = self.get_top() if top_item_tuple: self.delete_item(top_item_tuple[0] ) return top_item_tuple def _UpperCamelCase ( ) -> None: '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
80
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __lowerCAmelCase = None class __UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __lowerCAmelCase = PandasConfig def A (self : Tuple ): return datasets.DatasetInfo(features=self.config.features ) def A (self : Optional[int] , _lowerCAmelCase : List[Any] ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCAmelCase , (str, list, tuple) ): A = data_files if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A = [] for split_name, files in data_files.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCAmelCase , gen_kwargs={"""files""": files} ) ) return splits def A (self : Dict , _lowerCAmelCase : pa.Table ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example A = table_cast(_lowerCAmelCase , self.config.features.arrow_schema ) return pa_table def A (self : List[Any] , _lowerCAmelCase : Optional[Any] ): for i, file in enumerate(itertools.chain.from_iterable(_lowerCAmelCase ) ): with open(_lowerCAmelCase , """rb""" ) as f: A = pa.Table.from_pandas(pd.read_pickle(_lowerCAmelCase ) ) yield i, self._cast_table(_lowerCAmelCase )
258
0
import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class A__ ( A__ , A__ , A__ , unittest.TestCase ): lowerCAmelCase__ : Union[str, Any] = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase__ : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} lowerCAmelCase__ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase__ : List[str] = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"} ) lowerCAmelCase__ : int = IMAGE_TO_IMAGE_IMAGE_PARAMS def a__ ( self : str ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) __lowercase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) __lowercase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) __lowercase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=_lowerCAmelCase , set_alpha_to_one=_lowerCAmelCase , ) torch.manual_seed(0 ) __lowercase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __lowercase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) __lowercase = CLIPTextModel(_lowerCAmelCase ) __lowercase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __lowercase = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def a__ ( self : Optional[Any] , _UpperCAmelCase : Any , _UpperCAmelCase : List[Any]=0 ) -> int: """simple docstring""" if str(_lowerCAmelCase ).startswith('mps' ): __lowercase = torch.manual_seed(_lowerCAmelCase ) else: __lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) __lowercase = 2 __lowercase = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_lowerCAmelCase , device=torch.device(_lowerCAmelCase ) , ) __lowercase = floats_tensor(control_image.shape , rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) __lowercase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowercase = Image.fromarray(np.uinta(_lowerCAmelCase ) ).convert('RGB' ).resize((64, 64) ) __lowercase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def a__ ( self : Dict ) -> List[str]: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def a__ ( self : Dict ) -> Dict: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def a__ ( self : List[str] ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) class A__ ( A__ , A__ , unittest.TestCase ): lowerCAmelCase__ : Dict = StableDiffusionControlNetImgaImgPipeline lowerCAmelCase__ : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} lowerCAmelCase__ : List[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowerCAmelCase__ : Union[str, Any] = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def a__ ( self : List[Any] ) -> str: """simple docstring""" torch.manual_seed(0 ) __lowercase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) torch.manual_seed(0 ) def init_weights(_UpperCAmelCase : Dict ): if isinstance(_lowerCAmelCase , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) __lowercase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(_lowerCAmelCase ) torch.manual_seed(0 ) __lowercase = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(_lowerCAmelCase ) torch.manual_seed(0 ) __lowercase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=_lowerCAmelCase , set_alpha_to_one=_lowerCAmelCase , ) torch.manual_seed(0 ) __lowercase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) __lowercase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) __lowercase = CLIPTextModel(_lowerCAmelCase ) __lowercase = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) __lowercase = MultiControlNetModel([controlneta, controlneta] ) __lowercase = { 'unet': unet, 'controlnet': controlnet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def a__ ( self : Optional[int] , _UpperCAmelCase : int , _UpperCAmelCase : Dict=0 ) -> str: """simple docstring""" if str(_lowerCAmelCase ).startswith('mps' ): __lowercase = torch.manual_seed(_lowerCAmelCase ) else: __lowercase = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) __lowercase = 2 __lowercase = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_lowerCAmelCase , device=torch.device(_lowerCAmelCase ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=_lowerCAmelCase , device=torch.device(_lowerCAmelCase ) , ), ] __lowercase = floats_tensor(control_image[0].shape , rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) __lowercase = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowercase = Image.fromarray(np.uinta(_lowerCAmelCase ) ).convert('RGB' ).resize((64, 64) ) __lowercase = { 'prompt': 'A painting of a squirrel eating a burger', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'output_type': 'numpy', 'image': image, 'control_image': control_image, } return inputs def a__ ( self : Any ) -> Optional[int]: """simple docstring""" __lowercase = self.get_dummy_components() __lowercase = self.pipeline_class(**_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) __lowercase = 10.0 __lowercase = 4 __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = steps __lowercase = scale __lowercase = pipe(**_lowerCAmelCase )[0] __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = steps __lowercase = scale __lowercase = pipe(**_lowerCAmelCase , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = steps __lowercase = scale __lowercase = pipe(**_lowerCAmelCase , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] __lowercase = self.get_dummy_inputs(_lowerCAmelCase ) __lowercase = steps __lowercase = scale __lowercase = pipe(**_lowerCAmelCase , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 assert np.sum(np.abs(output_a - output_a ) ) > 1e-3 def a__ ( self : Dict ) -> Tuple: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3 ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def a__ ( self : Union[str, Any] ) -> Any: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3 ) def a__ ( self : List[str] ) -> Optional[int]: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2e-3 ) def a__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __lowercase = self.get_dummy_components() __lowercase = self.pipeline_class(**_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(_lowerCAmelCase ) except NotImplementedError: pass @slow @require_torch_gpu class A__ ( unittest.TestCase ): def a__ ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self : str ) -> Tuple: """simple docstring""" __lowercase = ControlNetModel.from_pretrained('lllyasviel/sd-controlnet-canny' ) __lowercase = StableDiffusionControlNetImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , safety_checker=_lowerCAmelCase , controlnet=_lowerCAmelCase ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=_lowerCAmelCase ) __lowercase = torch.Generator(device='cpu' ).manual_seed(0 ) __lowercase = 'evil space-punk bird' __lowercase = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ).resize((5_12, 5_12) ) __lowercase = load_image( 'https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png' ).resize((5_12, 5_12) ) __lowercase = pipe( _lowerCAmelCase , _lowerCAmelCase , control_image=_lowerCAmelCase , generator=_lowerCAmelCase , output_type='np' , num_inference_steps=50 , strength=0.6 , ) __lowercase = output.images[0] assert image.shape == (5_12, 5_12, 3) __lowercase = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy' ) assert np.abs(expected_image - image ).max() < 9e-2
325
'''simple docstring''' from collections import Counter from timeit import timeit def __a ( UpperCAmelCase = "" , ) ->bool: """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def __a ( UpperCAmelCase = "" ) ->bool: """simple docstring""" if len(UpperCAmelCase ) == 0: return True A = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string A = {} for character in lower_case_input_str: A = character_freq_dict.get(UpperCAmelCase , 0 ) + 1 A = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __a ( UpperCAmelCase = "" ) ->None: """simple docstring""" print("""\nFor string = """ , UpperCAmelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": _lowerCamelCase : Any = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) _lowerCamelCase : Any = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
258
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys A__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
82
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = '''encodec''' def __init__(self : List[Any] , _lowerCAmelCase : Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , _lowerCAmelCase : List[str]=2_4000 , _lowerCAmelCase : List[str]=1 , _lowerCAmelCase : List[str]=False , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : Dict=128 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : List[Any]=1 , _lowerCAmelCase : int=[8, 5, 4, 2] , _lowerCAmelCase : Any="weight_norm" , _lowerCAmelCase : List[str]=7 , _lowerCAmelCase : int=7 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : int=2 , _lowerCAmelCase : str=True , _lowerCAmelCase : str="reflect" , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Tuple=1.0 , _lowerCAmelCase : Tuple=1024 , _lowerCAmelCase : str=None , _lowerCAmelCase : Dict=True , **_lowerCAmelCase : List[str] , ): A = target_bandwidths A = sampling_rate A = audio_channels A = normalize A = chunk_length_s A = overlap A = hidden_size A = num_filters A = num_residual_layers A = upsampling_ratios A = norm_type A = kernel_size A = last_kernel_size A = residual_kernel_size A = dilation_growth_rate A = use_causal_conv A = pad_mode A = compress A = num_lstm_layers A = trim_right_ratio A = codebook_size A = codebook_dim if codebook_dim is not None else hidden_size A = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**_lowerCAmelCase ) @property def A (self : List[Any] ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def A (self : Union[str, Any] ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def A (self : Any ): A = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def A (self : List[str] ): return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
258
0
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer __UpperCamelCase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name __UpperCamelCase : str = '\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n >>> repo = "openai/shap-e-img2img"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n >>> image = load_image(image_url).convert("RGB")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n ```\n' @dataclass class __SCREAMING_SNAKE_CASE( A__ ): _UpperCAmelCase = 4_2 class __SCREAMING_SNAKE_CASE( A__ ): def __init__( self: str , UpperCamelCase: PriorTransformer , UpperCamelCase: CLIPVisionModel , UpperCamelCase: CLIPImageProcessor , UpperCamelCase: HeunDiscreteScheduler , UpperCamelCase: ShapERenderer , ) -> str: super().__init__() self.register_modules( prior=_lowerCAmelCase , image_encoder=_lowerCAmelCase , image_processor=_lowerCAmelCase , scheduler=_lowerCAmelCase , renderer=_lowerCAmelCase , ) def lowerCAmelCase_ ( self: Dict , UpperCamelCase: Tuple , UpperCamelCase: Any , UpperCamelCase: Tuple , UpperCamelCase: Any , UpperCamelCase: Tuple , UpperCamelCase: Optional[Any] ) -> int: if latents is None: snake_case__ = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) snake_case__ = latents.to(_lowerCAmelCase ) snake_case__ = latents * scheduler.init_noise_sigma return latents def lowerCAmelCase_ ( self: Union[str, Any] , UpperCamelCase: List[Any]=0 ) -> Any: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) snake_case__ = torch.device(F'''cuda:{gpu_id}''' ) snake_case__ = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCAmelCase , _lowerCAmelCase ) @property def lowerCAmelCase_ ( self: Optional[Any] ) -> Union[str, Any]: if self.device != torch.device('meta' ) or not hasattr(self.image_encoder , '_hf_hook' ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_lowerCAmelCase , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def lowerCAmelCase_ ( self: int , UpperCamelCase: Optional[int] , UpperCamelCase: Union[str, Any] , UpperCamelCase: Any , UpperCamelCase: Optional[int] , ) -> Dict: if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , torch.Tensor ): snake_case__ = torch.cat(_lowerCAmelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase , axis=0 ) if not isinstance(_lowerCAmelCase , torch.Tensor ): snake_case__ = self.image_processor(_lowerCAmelCase , return_tensors='pt' ).pixel_values[0].unsqueeze(0 ) snake_case__ = image.to(dtype=self.image_encoder.dtype , device=_lowerCAmelCase ) snake_case__ = self.image_encoder(_lowerCAmelCase )['last_hidden_state'] snake_case__ = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 snake_case__ = image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: snake_case__ = torch.zeros_like(_lowerCAmelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes snake_case__ = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_lowerCAmelCase ) def __call__( self: List[Any] , UpperCamelCase: Union[PIL.Image.Image, List[PIL.Image.Image]] , UpperCamelCase: int = 1 , UpperCamelCase: int = 25 , UpperCamelCase: Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase: Optional[torch.FloatTensor] = None , UpperCamelCase: float = 4.0 , UpperCamelCase: int = 64 , UpperCamelCase: Optional[str] = "pil" , UpperCamelCase: bool = True , ) -> List[Any]: if isinstance(_lowerCAmelCase , PIL.Image.Image ): snake_case__ = 1 elif isinstance(_lowerCAmelCase , torch.Tensor ): snake_case__ = image.shape[0] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): snake_case__ = len(_lowerCAmelCase ) else: raise ValueError( F'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCAmelCase )}''' ) snake_case__ = self._execution_device snake_case__ = batch_size * num_images_per_prompt snake_case__ = guidance_scale > 1.0 snake_case__ = self._encode_image(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # prior self.scheduler.set_timesteps(_lowerCAmelCase , device=_lowerCAmelCase ) snake_case__ = self.scheduler.timesteps snake_case__ = self.prior.config.num_embeddings snake_case__ = self.prior.config.embedding_dim snake_case__ = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim snake_case__ = latents.reshape(latents.shape[0] , _lowerCAmelCase , _lowerCAmelCase ) for i, t in enumerate(self.progress_bar(_lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance snake_case__ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents snake_case__ = self.scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) snake_case__ = self.prior( _lowerCAmelCase , timestep=_lowerCAmelCase , proj_embedding=_lowerCAmelCase , ).predicted_image_embedding # remove the variance snake_case__ , snake_case__ = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: snake_case__ , snake_case__ = noise_pred.chunk(2 ) snake_case__ = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) snake_case__ = self.scheduler.step( _lowerCAmelCase , timestep=_lowerCAmelCase , sample=_lowerCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_lowerCAmelCase ) snake_case__ = [] for i, latent in enumerate(_lowerCAmelCase ): print() snake_case__ = self.renderer.decode( latent[None, :] , _lowerCAmelCase , size=_lowerCAmelCase , ray_batch_size=40_96 , n_coarse_samples=64 , n_fine_samples=1_28 , ) images.append(_lowerCAmelCase ) snake_case__ = torch.stack(_lowerCAmelCase ) if output_type not in ["np", "pil"]: raise ValueError(F'''Only the output types `pil` and `np` are supported not output_type={output_type}''' ) snake_case__ = images.cpu().numpy() if output_type == "pil": snake_case__ = [self.numpy_to_pil(_lowerCAmelCase ) for image in images] # Offload last model to CPU if hasattr(self , 'final_offload_hook' ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_lowerCAmelCase )
307
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available _lowerCamelCase : Dict = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys _lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
258
0
from __future__ import annotations import numpy as np def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Optional[int]: return np.maximum(0 , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
20
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : str ): A = """ylacombe/bark-small""" A = tempfile.mkdtemp() A = """en_speaker_1""" A = """This is a test string""" A = """speaker_embeddings_path.json""" A = """speaker_embeddings""" def A (self : Optional[Any] , **_lowerCAmelCase : Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **_lowerCAmelCase ) def A (self : Dict ): shutil.rmtree(self.tmpdirname ) def A (self : Optional[Any] ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) A = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def A (self : int ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) A = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) A = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def A (self : Union[str, Any] ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) A = 35 A = 2 A = 8 A = { """semantic_prompt""": np.ones(_lowerCAmelCase ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file A = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(_lowerCAmelCase , **_lowerCAmelCase ) A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub A = processor(text=self.input_string , voice_preset=self.voice_preset ) def A (self : str ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) A = processor(text=self.input_string ) A = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
258
0
import torch from ..models.auto import AutoModelForSequenceClassification, AutoTokenizer from .base import PipelineTool class UpperCAmelCase ( A__ ): '''simple docstring''' __UpperCamelCase : int = '''facebook/bart-large-mnli''' __UpperCamelCase : Tuple = ( '''This is a tool that classifies an English text using provided labels. It takes two inputs: `text`, which ''' '''should be the text to classify, and `labels`, which should be the list of labels to use for classification. ''' '''It returns the most likely label in the list of provided `labels` for the input text.''' ) __UpperCamelCase : Dict = '''text_classifier''' __UpperCamelCase : List[Any] = AutoTokenizer __UpperCamelCase : Any = AutoModelForSequenceClassification __UpperCamelCase : List[str] = ['''text''', ['''text''']] __UpperCamelCase : Optional[Any] = ['''text'''] def __magic_name__ ( self : Optional[int] ): """simple docstring""" super().setup() _A: Optional[Any] = self.model.config _A: List[Any] = -1 for idx, label in config.idalabel.items(): if label.lower().startswith('''entail''' ): _A: List[str] = int(_lowerCAmelCase ) if self.entailment_id == -1: raise ValueError('''Could not determine the entailment ID from the model config, please pass it at init.''' ) def __magic_name__ ( self : Union[str, Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : List[Any] ): """simple docstring""" _A: str = labels return self.pre_processor( [text] * len(_lowerCAmelCase ) , [F"""This example is {label}""" for label in labels] , return_tensors='''pt''' , padding='''max_length''' , ) def __magic_name__ ( self : Optional[int] , lowerCAmelCase_ : Dict ): """simple docstring""" _A: Union[str, Any] = outputs.logits _A: Any = torch.argmax(logits[:, 2] ).item() return self._labels[label_id]
121
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan _lowerCamelCase : List[Any] = 6_3_7_8_1_3_7.0 _lowerCamelCase : List[Any] = 6_3_5_6_7_5_2.3_1_4_2_4_5 _lowerCamelCase : Optional[int] = 637_8137 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" A = (AXIS_A - AXIS_B) / AXIS_A A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = radians(UpperCAmelCase ) A = radians(UpperCAmelCase ) # Equation A = sin((phi_a - phi_a) / 2 ) A = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda A = sqrt(sin_sq_phi + (cos(UpperCAmelCase ) * cos(UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
258
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A =logging.get_logger(__name__) __A ={ 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json', 'google/bigbird-roberta-large': 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json', 'google/bigbird-base-trivia-itc': 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json', # See all BigBird models at https://huggingface.co/models?filter=big_bird } class _snake_case ( A__ ): lowerCAmelCase :Optional[int] = '''big_bird''' def __init__( self , _lowerCamelCase=5_0358 , _lowerCamelCase=768 , _lowerCamelCase=12 , _lowerCamelCase=12 , _lowerCamelCase=3072 , _lowerCamelCase="gelu_new" , _lowerCamelCase=0.1 , _lowerCamelCase=0.1 , _lowerCamelCase=4096 , _lowerCamelCase=2 , _lowerCamelCase=0.02 , _lowerCamelCase=1e-1_2 , _lowerCamelCase=True , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=66 , _lowerCamelCase="block_sparse" , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=64 , _lowerCamelCase=3 , _lowerCamelCase=None , **_lowerCamelCase , ): super().__init__( pad_token_id=_lowerCAmelCase , bos_token_id=_lowerCAmelCase , eos_token_id=_lowerCAmelCase , sep_token_id=_lowerCAmelCase , **_lowerCAmelCase , ) UpperCAmelCase__ : Tuple = vocab_size UpperCAmelCase__ : Tuple = max_position_embeddings UpperCAmelCase__ : Dict = hidden_size UpperCAmelCase__ : Tuple = num_hidden_layers UpperCAmelCase__ : Any = num_attention_heads UpperCAmelCase__ : Optional[int] = intermediate_size UpperCAmelCase__ : Any = hidden_act UpperCAmelCase__ : Union[str, Any] = hidden_dropout_prob UpperCAmelCase__ : int = attention_probs_dropout_prob UpperCAmelCase__ : int = initializer_range UpperCAmelCase__ : Union[str, Any] = type_vocab_size UpperCAmelCase__ : Any = layer_norm_eps UpperCAmelCase__ : Optional[Any] = use_cache UpperCAmelCase__ : Optional[Any] = rescale_embeddings UpperCAmelCase__ : str = attention_type UpperCAmelCase__ : int = use_bias UpperCAmelCase__ : str = block_size UpperCAmelCase__ : str = num_random_blocks UpperCAmelCase__ : List[str] = classifier_dropout class _snake_case ( A__ ): @property def snake_case__ ( self): if self.task == "multiple-choice": UpperCAmelCase__ : Optional[int] = {0: """batch""", 1: """choice""", 2: """sequence"""} else: UpperCAmelCase__ : List[Any] = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ])
163
'''simple docstring''' import os import sys import unittest _lowerCamelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) _lowerCamelCase : str = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') _lowerCamelCase : Tuple = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : Any ): A = get_test_to_tester_mapping(_lowerCAmelCase ) A = get_test_to_tester_mapping(_lowerCAmelCase ) A = {"""BertModelTest""": """BertModelTester"""} A = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : str ): A = get_model_to_test_mapping(_lowerCAmelCase ) A = get_model_to_test_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): A = get_model_to_tester_mapping(_lowerCAmelCase ) A = get_model_to_tester_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase )
258
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase ( A__ , A__ , unittest.TestCase ): """simple docstring""" UpperCAmelCase = CycleDiffusionPipeline UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { """negative_prompt""", """height""", """width""", """negative_prompt_embeds""", } UpperCAmelCase = PipelineTesterMixin.required_optional_params - {"""latents"""} UpperCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""source_prompt"""} ) UpperCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def _snake_case ( self ) -> Any: torch.manual_seed(0 ) _UpperCAmelCase : Any = UNetaDConditionModel( block_out_channels=(32, 64) ,layers_per_block=2 ,sample_size=32 ,in_channels=4 ,out_channels=4 ,down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,cross_attention_dim=32 ,) _UpperCAmelCase : List[str] = DDIMScheduler( beta_start=0.0_0085 ,beta_end=0.012 ,beta_schedule="""scaled_linear""" ,num_train_timesteps=1_000 ,clip_sample=_lowerCAmelCase ,set_alpha_to_one=_lowerCAmelCase ,) torch.manual_seed(0 ) _UpperCAmelCase : Optional[Any] = AutoencoderKL( block_out_channels=[32, 64] ,in_channels=3 ,out_channels=3 ,down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,latent_channels=4 ,) torch.manual_seed(0 ) _UpperCAmelCase : int = CLIPTextConfig( bos_token_id=0 ,eos_token_id=2 ,hidden_size=32 ,intermediate_size=37 ,layer_norm_eps=1E-0_5 ,num_attention_heads=4 ,num_hidden_layers=5 ,pad_token_id=1 ,vocab_size=1_000 ,) _UpperCAmelCase : Dict = CLIPTextModel(_lowerCAmelCase ) _UpperCAmelCase : int = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) _UpperCAmelCase : Any = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _snake_case ( self ,a_ ,a_=0 ) -> List[str]: _UpperCAmelCase : Any = floats_tensor((1, 3, 32, 32) ,rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) _UpperCAmelCase : List[str] = image / 2 + 0.5 if str(_lowerCAmelCase ).startswith("""mps""" ): _UpperCAmelCase : int = torch.manual_seed(_lowerCAmelCase ) else: _UpperCAmelCase : Union[str, Any] = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) _UpperCAmelCase : Optional[int] = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def _snake_case ( self ) -> Any: _UpperCAmelCase : Dict = """cpu""" # ensure determinism for the device-dependent torch.Generator _UpperCAmelCase : Any = self.get_dummy_components() _UpperCAmelCase : int = CycleDiffusionPipeline(**_lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _UpperCAmelCase : Any = self.get_dummy_inputs(_lowerCAmelCase ) _UpperCAmelCase : List[Any] = pipe(**_lowerCAmelCase ) _UpperCAmelCase : Tuple = output.images _UpperCAmelCase : Dict = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) _UpperCAmelCase : Any = np.array([0.4459, 0.4943, 0.4544, 0.6643, 0.5474, 0.4327, 0.5701, 0.5959, 0.5179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf(torch_device != """cuda""" ,"""This test requires a GPU""" ) def _snake_case ( self ) -> Any: _UpperCAmelCase : Optional[Any] = self.get_dummy_components() for name, module in components.items(): if hasattr(_lowerCAmelCase ,"""half""" ): _UpperCAmelCase : Optional[Any] = module.half() _UpperCAmelCase : str = CycleDiffusionPipeline(**_lowerCAmelCase ) _UpperCAmelCase : Optional[int] = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) _UpperCAmelCase : str = self.get_dummy_inputs(_lowerCAmelCase ) _UpperCAmelCase : Tuple = pipe(**_lowerCAmelCase ) _UpperCAmelCase : Any = output.images _UpperCAmelCase : Optional[int] = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) _UpperCAmelCase : List[Any] = np.array([0.3506, 0.4543, 0.446, 0.4575, 0.5195, 0.4155, 0.5273, 0.518, 0.4116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def _snake_case ( self ) -> Optional[Any]: return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def _snake_case ( self ) -> Tuple: return super().test_inference_batch_single_identical() @skip_mps def _snake_case ( self ) -> Optional[Any]: return super().test_dict_tuple_outputs_equivalent() @skip_mps def _snake_case ( self ) -> str: return super().test_save_load_optional_components() @skip_mps def _snake_case ( self ) -> Any: return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class lowercase ( unittest.TestCase ): """simple docstring""" def _snake_case ( self ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ) -> Dict: _UpperCAmelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) _UpperCAmelCase : List[str] = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) _UpperCAmelCase : Dict = init_image.resize((512, 512) ) _UpperCAmelCase : str = """CompVis/stable-diffusion-v1-4""" _UpperCAmelCase : List[str] = DDIMScheduler.from_pretrained(_lowerCAmelCase ,subfolder="""scheduler""" ) _UpperCAmelCase : Union[str, Any] = CycleDiffusionPipeline.from_pretrained( _lowerCAmelCase ,scheduler=_lowerCAmelCase ,safety_checker=_lowerCAmelCase ,torch_dtype=torch.floataa ,revision="""fp16""" ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() _UpperCAmelCase : Union[str, Any] = """A black colored car""" _UpperCAmelCase : Dict = """A blue colored car""" _UpperCAmelCase : Tuple = torch.manual_seed(0 ) _UpperCAmelCase : str = pipe( prompt=_lowerCAmelCase ,source_prompt=_lowerCAmelCase ,image=_lowerCAmelCase ,num_inference_steps=100 ,eta=0.1 ,strength=0.85 ,guidance_scale=3 ,source_guidance_scale=1 ,generator=_lowerCAmelCase ,output_type="""np""" ,) _UpperCAmelCase : Optional[Any] = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5E-1 def _snake_case ( self ) -> Tuple: _UpperCAmelCase : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) _UpperCAmelCase : Any = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) _UpperCAmelCase : Union[str, Any] = init_image.resize((512, 512) ) _UpperCAmelCase : str = """CompVis/stable-diffusion-v1-4""" _UpperCAmelCase : Optional[int] = DDIMScheduler.from_pretrained(_lowerCAmelCase ,subfolder="""scheduler""" ) _UpperCAmelCase : Optional[Any] = CycleDiffusionPipeline.from_pretrained(_lowerCAmelCase ,scheduler=_lowerCAmelCase ,safety_checker=_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() _UpperCAmelCase : Any = """A black colored car""" _UpperCAmelCase : List[str] = """A blue colored car""" _UpperCAmelCase : Tuple = torch.manual_seed(0 ) _UpperCAmelCase : List[Any] = pipe( prompt=_lowerCAmelCase ,source_prompt=_lowerCAmelCase ,image=_lowerCAmelCase ,num_inference_steps=100 ,eta=0.1 ,strength=0.85 ,guidance_scale=3 ,source_guidance_scale=1 ,generator=_lowerCAmelCase ,output_type="""np""" ,) _UpperCAmelCase : Any = output.images assert np.abs(image - expected_image ).max() < 2E-2
215
'''simple docstring''' from __future__ import annotations def __a ( UpperCAmelCase , UpperCAmelCase ) ->Tuple: """simple docstring""" if len(UpperCAmelCase ) <= 1 or n <= 1: return insert_next(UpperCAmelCase , n - 1 ) rec_insertion_sort(UpperCAmelCase , n - 1 ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if index >= len(UpperCAmelCase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order A , A = ( collection[index], collection[index - 1], ) insert_next(UpperCAmelCase , index + 1 ) if __name__ == "__main__": _lowerCamelCase : List[Any] = input('Enter integers separated by spaces: ') _lowerCamelCase : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
258
0
class A ( A__ ): pass class A ( A__ ): pass class A : def __init__(self ): __lowercase= [ [], [], [], ] def _A (self , lowerCAmelCase , lowerCAmelCase ): try: if len(self.queues[priority] ) >= 1_0_0: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(_lowerCAmelCase ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def _A (self ): for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__(self ): return "\n".join(f'Priority {i}: {q}' for i, q in enumerate(self.queues ) ) class A : def __init__(self ): __lowercase= [] def _A (self , lowerCAmelCase ): if len(self.queue ) == 1_0_0: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(_lowerCAmelCase ) def _A (self ): if not self.queue: raise UnderFlowError('The queue is empty' ) else: __lowercase= min(self.queue ) self.queue.remove(_lowerCAmelCase ) return data def __str__(self ): return str(self.queue ) def _lowerCamelCase( ) -> Optional[Any]: '''simple docstring''' __lowercase= FixedPriorityQueue() fpq.enqueue(0 , 1_0 ) fpq.enqueue(1 , 7_0 ) fpq.enqueue(0 , 1_0_0 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 6_4 ) fpq.enqueue(0 , 1_2_8 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _lowerCamelCase( ) -> Any: '''simple docstring''' __lowercase= ElementPriorityQueue() epq.enqueue(1_0 ) epq.enqueue(7_0 ) epq.enqueue(1_0_0 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(6_4 ) epq.enqueue(1_2_8 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
295
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def __a ( UpperCAmelCase ) ->Tuple: # picklable for multiprocessing """simple docstring""" return x.sum() def __a ( UpperCAmelCase ) ->int: # picklable for multiprocessing """simple docstring""" return i + 1 @dataclass class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = 42 __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def A (self : Tuple ): A = {} A = [] A = 1 A = [1, 2] A = {"""a""": 1, """b""": 2} A = {"""a""": [1, 2], """b""": [3, 4]} A = {"""a""": {"""1""": 1}, """b""": 2} A = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} A = {} A = [] A = 2 A = [2, 3] A = {"""a""": 2, """b""": 3} A = {"""a""": [2, 3], """b""": [4, 5]} A = {"""a""": {"""1""": 2}, """b""": 3} A = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) A = 2 self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) A = {"""a""": np.eye(2 ), """b""": np.zeros(3 ), """c""": np.ones(2 )} A = {"""a""": 2, """b""": 0, """c""": 2} A = { """a""": np.eye(2 ).astype(_lowerCAmelCase ), """b""": np.zeros(3 ).astype(_lowerCAmelCase ), """c""": np.ones(2 ).astype(_lowerCAmelCase ), } self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(_lowerCAmelCase ): # can't pickle a local lambda map_nested(lambda _lowerCAmelCase : x + 1 , _lowerCAmelCase , num_proc=_lowerCAmelCase ) def A (self : List[Any] ): A = {"""a""": 1, """b""": 2} A = {"""a""": 3, """b""": 4} A = {"""a""": 5, """b""": 6} A = sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = '''bar''' A = Foo() self.assertEqual(foo.my_attr , """bar""" ) with temporary_assignment(_lowerCAmelCase , """my_attr""" , """BAR""" ): self.assertEqual(foo.my_attr , """BAR""" ) self.assertEqual(foo.my_attr , """bar""" ) @pytest.mark.parametrize( """iterable_length, num_proc, expected_num_proc""" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Any: """simple docstring""" with patch("""datasets.utils.py_utils._single_map_nested""" ) as mock_single_map_nested, patch( """datasets.parallel.parallel.Pool""" ) as mock_multiprocessing_pool: A = {f"""{i}""": i for i in range(UpperCAmelCase )} A = map_nested(lambda UpperCAmelCase : x + 10 , UpperCAmelCase , num_proc=UpperCAmelCase , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class __UpperCAmelCase ( A__ ): '''simple docstring''' @require_tf def A (self : Dict ): import tensorflow as tf from tensorflow.keras import layers A = layers.Dense(2 ) def gen_random_output(): A = tf.random.uniform((1, 3) ) return model(_lowerCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def A (self : Tuple ): import torch def gen_random_output(): A = torch.nn.Linear(3 , 2 ) A = torch.rand(1 , 3 ) return model(_lowerCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def A (self : str ): def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): A = gen_random_output() with temp_seed(42 ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("""input_data""" , [{}] ) def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).data assert output_data == input_data @pytest.mark.parametrize( """data, expected_output""" , [ ({}, []), ([], []), ("""foo""", ["""foo"""]), (["""foo""", """bar"""], ["""foo""", """bar"""]), ([["""foo""", """bar"""]], ["""foo""", """bar"""]), ([[["""foo"""], ["""bar"""]]], ["""foo""", """bar"""]), ([[["""foo"""], """bar"""]], ["""foo""", """bar"""]), ({"""a""": 1, """b""": 2}, [1, 2]), ({"""a""": [1, 2], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[[3], [4]]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, [4]]}, [1, 2, 3, 4]), ({"""a""": {"""1""": 1}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": [2]}, [1, 2]), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->List[Any]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).flatten() assert output == expected_output def __a ( ) ->Optional[Any]: """simple docstring""" A = A(x=1 , y="""foobar""" ) A = {"""x""": 1, """y""": """foobar"""} assert asdict(UpperCAmelCase ) == expected_output A = {"""a""": {"""b""": A(x=10 , y="""foo""" )}, """c""": [A(x=20 , y="""bar""" )]} A = {"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]} assert asdict(UpperCAmelCase ) == expected_output with pytest.raises(UpperCAmelCase ): asdict([1, A(x=10 , y="""foo""" )] ) def __a ( UpperCAmelCase ) ->Tuple: """simple docstring""" return text.split() def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def __a ( ) ->Optional[int]: """simple docstring""" with Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: A = [] for yield_time, content in iflatmap_unordered( UpperCAmelCase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"""content""": """a"""}, {"""content""": """b"""}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(UpperCAmelCase ) assert out.count("""a""" ) == 2 assert out.count("""b""" ) == 2 assert len(UpperCAmelCase ) == 4
258
0
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() A : Dict = logging.get_logger(__name__) A : Any = 'https://openaipublic.azureedge.net/jukebox/models/' A : 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 a__ ( __UpperCamelCase ): if key.endswith(".model.1.bias" ) and len(key.split("." ) ) > 1_0: SCREAMING_SNAKE_CASE_ = key.replace(".model.1.bias" , ".conv1d_1.bias" ) elif key.endswith(".model.1.weight" ) and len(key.split("." ) ) > 1_0: SCREAMING_SNAKE_CASE_ = key.replace(".model.1.weight" , ".conv1d_1.weight" ) elif key.endswith(".model.3.bias" ) and len(key.split("." ) ) > 1_0: SCREAMING_SNAKE_CASE_ = key.replace(".model.3.bias" , ".conv1d_2.bias" ) elif key.endswith(".model.3.weight" ) and len(key.split("." ) ) > 1_0: SCREAMING_SNAKE_CASE_ = key.replace(".model.3.weight" , ".conv1d_2.weight" ) if "conditioner_blocks.0." in key: SCREAMING_SNAKE_CASE_ = key.replace("conditioner_blocks.0" , "conditioner_blocks" ) if "prime_prior" in key: SCREAMING_SNAKE_CASE_ = key.replace("prime_prior" , "encoder" ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: SCREAMING_SNAKE_CASE_ = 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: SCREAMING_SNAKE_CASE_ = 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 a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): SCREAMING_SNAKE_CASE_ = {} import re SCREAMING_SNAKE_CASE_ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile( r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile( r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = re.compile( r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)" ) SCREAMING_SNAKE_CASE_ = 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(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_encoder_block_conv_in.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[2] ) * 2 + int(groups[3] ) SCREAMING_SNAKE_CASE_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_encoder_block_conv_in.sub(__UpperCamelCase , __UpperCamelCase ) elif re_encoder_block_resnet.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_encoder_block_resnet.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[2] ) * 2 + int(groups[3] ) SCREAMING_SNAKE_CASE_ = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' SCREAMING_SNAKE_CASE_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = prefix + resnet_block SCREAMING_SNAKE_CASE_ = re_encoder_block_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_encoder_block_proj_out.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_encoder_block_proj_out.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_encoder_block_proj_out.sub(__UpperCamelCase , __UpperCamelCase ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_decoder_block_conv_out.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 SCREAMING_SNAKE_CASE_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_decoder_block_conv_out.sub(__UpperCamelCase , __UpperCamelCase ) elif re_decoder_block_resnet.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_decoder_block_resnet.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[2] ) * 2 + int(groups[3] ) - 2 SCREAMING_SNAKE_CASE_ = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' SCREAMING_SNAKE_CASE_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = prefix + resnet_block SCREAMING_SNAKE_CASE_ = re_decoder_block_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_decoder_block_proj_in.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_decoder_block_proj_in.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_decoder_block_proj_in.sub(__UpperCamelCase , __UpperCamelCase ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_prior_cond_conv_out.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 SCREAMING_SNAKE_CASE_ = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_prior_cond_conv_out.sub(__UpperCamelCase , __UpperCamelCase ) elif re_prior_cond_resnet.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_prior_cond_resnet.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = int(groups[1] ) * 2 + int(groups[2] ) - 2 SCREAMING_SNAKE_CASE_ = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE_ = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' SCREAMING_SNAKE_CASE_ = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = prefix + resnet_block SCREAMING_SNAKE_CASE_ = re_prior_cond_resnet.sub(__UpperCamelCase , __UpperCamelCase ) elif re_prior_cond_proj_in.fullmatch(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = re_prior_cond_proj_in.match(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = regex_match.groups() SCREAMING_SNAKE_CASE_ = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' SCREAMING_SNAKE_CASE_ = re_prior_cond_proj_in.sub(__UpperCamelCase , __UpperCamelCase ) # keep original key else: SCREAMING_SNAKE_CASE_ = original_key SCREAMING_SNAKE_CASE_ = replace_key(__UpperCamelCase ) 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: SCREAMING_SNAKE_CASE_ = model_state_dict[F'''{key_prefix}.{key}'''] print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) SCREAMING_SNAKE_CASE_ = original_key SCREAMING_SNAKE_CASE_ = original_key SCREAMING_SNAKE_CASE_ = value return new_dict @torch.no_grad() def a__ ( __UpperCamelCase=None , __UpperCamelCase=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): SCREAMING_SNAKE_CASE_ = requests.get(F'''{PREFIX}{file}''' , allow_redirects=__UpperCamelCase ) os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=__UpperCamelCase ) open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , "wb" ).write(r.content ) SCREAMING_SNAKE_CASE_ = MODEL_MAPPING[model_name.split("/" )[-1]] SCREAMING_SNAKE_CASE_ = JukeboxConfig.from_pretrained(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = JukeboxModel(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = {} for i, dict_name in enumerate(__UpperCamelCase ): SCREAMING_SNAKE_CASE_ = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )["model"] SCREAMING_SNAKE_CASE_ = {} for k in old_dic.keys(): if k.endswith(".b" ): SCREAMING_SNAKE_CASE_ = old_dic[k] elif k.endswith(".w" ): SCREAMING_SNAKE_CASE_ = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: SCREAMING_SNAKE_CASE_ = old_dic[k] else: SCREAMING_SNAKE_CASE_ = old_dic[k] SCREAMING_SNAKE_CASE_ = "vqvae" if i == 0 else F'''priors.{3 - i}''' SCREAMING_SNAKE_CASE_ = fix_jukebox_keys(__UpperCamelCase , model.state_dict() , __UpperCamelCase , __UpperCamelCase ) weight_dict.append(__UpperCamelCase ) SCREAMING_SNAKE_CASE_ = weight_dict.pop(0 ) model.vqvae.load_state_dict(__UpperCamelCase ) for i in range(len(__UpperCamelCase ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(__UpperCamelCase ).mkdir(exist_ok=__UpperCamelCase ) with open(F'''{pytorch_dump_folder_path}/mapping.json''' , "w" ) as txtfile: json.dump(__UpperCamelCase , __UpperCamelCase ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(__UpperCamelCase ) return weight_dict if __name__ == "__main__": A : int = 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.", ) A : Optional[Any] = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __a ( ) ->None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
258
0
import argparse import os import re _SCREAMING_SNAKE_CASE = 'src/transformers' # Pattern that looks at the indentation in a line. _SCREAMING_SNAKE_CASE = re.compile(R'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. _SCREAMING_SNAKE_CASE = re.compile(R'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. _SCREAMING_SNAKE_CASE = re.compile(R'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. _SCREAMING_SNAKE_CASE = re.compile(R'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. _SCREAMING_SNAKE_CASE = re.compile(R'\[([^\]]+)\]') def snake_case ( snake_case__ :int) -> Any: _A = _re_indent.search(snake_case__) return "" if search is None else search.groups()[0] def snake_case ( snake_case__ :List[str] , snake_case__ :Any="" , snake_case__ :int=None , snake_case__ :Union[str, Any]=None) -> Optional[Any]: _A = 0 _A = code.split("""\n""") if start_prompt is not None: while not lines[index].startswith(snake_case__): index += 1 _A = ["""\n""".join(lines[:index])] else: _A = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). _A = [lines[index]] index += 1 while index < len(snake_case__) and (end_prompt is None or not lines[index].startswith(snake_case__)): if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level: if len(snake_case__) > 0 and get_indent(current_block[-1]).startswith(indent_level + """ """): current_block.append(lines[index]) blocks.append("""\n""".join(snake_case__)) if index < len(snake_case__) - 1: _A = [lines[index + 1]] index += 1 else: _A = [] else: blocks.append("""\n""".join(snake_case__)) _A = [lines[index]] else: current_block.append(lines[index]) index += 1 # Adds current block if it's nonempty. if len(snake_case__) > 0: blocks.append("""\n""".join(snake_case__)) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(snake_case__): blocks.append("""\n""".join(lines[index:])) return blocks def snake_case ( snake_case__ :Dict) -> Optional[int]: def _inner(snake_case__ :Dict): return key(snake_case__).lower().replace("""_""" , """""") return _inner def snake_case ( snake_case__ :Any , snake_case__ :Dict=None) -> List[str]: def noop(snake_case__ :Dict): return x if key is None: _A = noop # Constants are all uppercase, they go first. _A = [obj for obj in objects if key(snake_case__).isupper()] # Classes are not all uppercase but start with a capital, they go second. _A = [obj for obj in objects if key(snake_case__)[0].isupper() and not key(snake_case__).isupper()] # Functions begin with a lowercase, they go last. _A = [obj for obj in objects if not key(snake_case__)[0].isupper()] _A = ignore_underscore(snake_case__) return sorted(snake_case__ , key=snake_case__) + sorted(snake_case__ , key=snake_case__) + sorted(snake_case__ , key=snake_case__) def snake_case ( snake_case__ :str) -> int: def _replace(snake_case__ :List[str]): _A = match.groups()[0] if "," not in imports: return F'''[{imports}]''' _A = [part.strip().replace("""\"""" , """""") for part in imports.split(""",""")] # We will have a final empty element if the line finished with a comma. if len(keys[-1]) == 0: _A = keys[:-1] return "[" + ", ".join([F'''\"{k}\"''' for k in sort_objects(snake_case__)]) + "]" _A = import_statement.split("""\n""") if len(snake_case__) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. _A = 2 if lines[1].strip() == """[""" else 1 _A = [(i, _re_strip_line.search(snake_case__).groups()[0]) for i, line in enumerate(lines[idx:-idx])] _A = sort_objects(snake_case__ , key=lambda snake_case__: x[1]) _A = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) elif len(snake_case__) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1]) is not None: _A = _re_bracket_content.sub(_replace , lines[1]) else: _A = [part.strip().replace("""\"""" , """""") for part in lines[1].split(""",""")] # We will have a final empty element if the line finished with a comma. if len(keys[-1]) == 0: _A = keys[:-1] _A = get_indent(lines[1]) + """, """.join([F'''\"{k}\"''' for k in sort_objects(snake_case__)]) return "\n".join(snake_case__) else: # Finally we have to deal with imports fitting on one line _A = _re_bracket_content.sub(_replace , snake_case__) return import_statement def snake_case ( snake_case__ :Optional[Any] , snake_case__ :List[str]=True) -> str: with open(snake_case__ , encoding="""utf-8""") as f: _A = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 _A = split_code_in_indented_blocks( snake_case__ , start_prompt="""_import_structure = {""" , end_prompt="""if TYPE_CHECKING:""") # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(snake_case__) - 1): # Check if the block contains some `_import_structure`s thingy to sort. _A = main_blocks[block_idx] _A = block.split("""\n""") # Get to the start of the imports. _A = 0 while line_idx < len(snake_case__) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: _A = len(snake_case__) else: line_idx += 1 if line_idx >= len(snake_case__): continue # Ignore beginning and last line: they don't contain anything. _A = """\n""".join(block_lines[line_idx:-1]) _A = get_indent(block_lines[1]) # Slit the internal block into blocks of indent level 1. _A = split_code_in_indented_blocks(snake_case__ , indent_level=snake_case__) # We have two categories of import key: list or _import_structure[key].append/extend _A = _re_direct_key if """_import_structure = {""" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. _A = [(pattern.search(snake_case__).groups()[0] if pattern.search(snake_case__) is not None else None) for b in internal_blocks] # We only sort the lines with a key. _A = [(i, key) for i, key in enumerate(snake_case__) if key is not None] _A = [x[0] for x in sorted(snake_case__ , key=lambda snake_case__: x[1])] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. _A = 0 _A = [] for i in range(len(snake_case__)): if keys[i] is None: reorderded_blocks.append(internal_blocks[i]) else: _A = sort_objects_in_import(internal_blocks[sorted_indices[count]]) reorderded_blocks.append(snake_case__) count += 1 # And we put our main block back together with its first and last line. _A = """\n""".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]) if code != "\n".join(snake_case__): if check_only: return True else: print(F'''Overwriting {file}.''') with open(snake_case__ , """w""" , encoding="""utf-8""") as f: f.write("""\n""".join(snake_case__)) def snake_case ( snake_case__ :Any=True) -> Dict: _A = [] for root, _, files in os.walk(snake_case__): if "__init__.py" in files: _A = sort_imports(os.path.join(snake_case__ , """__init__.py""") , check_only=snake_case__) if result: _A = [os.path.join(snake_case__ , """__init__.py""")] if len(snake_case__) > 0: raise ValueError(F'''Would overwrite {len(snake_case__)} files, run `make style`.''') if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') _SCREAMING_SNAKE_CASE = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
180
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase : str = '\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n >>> repo = "openai/shap-e-img2img"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n >>> image = load_image(image_url).convert("RGB")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n ```\n' @dataclass class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : str , _lowerCAmelCase : PriorTransformer , _lowerCAmelCase : CLIPVisionModel , _lowerCAmelCase : CLIPImageProcessor , _lowerCAmelCase : HeunDiscreteScheduler , _lowerCAmelCase : ShapERenderer , ): super().__init__() self.register_modules( prior=_lowerCAmelCase , image_encoder=_lowerCAmelCase , image_processor=_lowerCAmelCase , scheduler=_lowerCAmelCase , renderer=_lowerCAmelCase , ) def A (self : Dict , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[Any] ): if latents is None: A = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) A = latents.to(_lowerCAmelCase ) A = latents * scheduler.init_noise_sigma return latents def A (self : Union[str, Any] , _lowerCAmelCase : List[Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A = torch.device(F"""cuda:{gpu_id}""" ) A = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCAmelCase , _lowerCAmelCase ) @property def A (self : Optional[Any] ): if self.device != torch.device("""meta""" ) or not hasattr(self.image_encoder , """_hf_hook""" ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_lowerCAmelCase , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def A (self : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Optional[int] , ): if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , torch.Tensor ): A = torch.cat(_lowerCAmelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase , axis=0 ) if not isinstance(_lowerCAmelCase , torch.Tensor ): A = self.image_processor(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values[0].unsqueeze(0 ) A = image.to(dtype=self.image_encoder.dtype , device=_lowerCAmelCase ) A = self.image_encoder(_lowerCAmelCase )["""last_hidden_state"""] A = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 A = image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: A = torch.zeros_like(_lowerCAmelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_lowerCAmelCase ) def __call__(self : List[Any] , _lowerCAmelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , _lowerCAmelCase : int = 1 , _lowerCAmelCase : int = 25 , _lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCAmelCase : Optional[torch.FloatTensor] = None , _lowerCAmelCase : float = 4.0 , _lowerCAmelCase : int = 64 , _lowerCAmelCase : Optional[str] = "pil" , _lowerCAmelCase : bool = True , ): if isinstance(_lowerCAmelCase , PIL.Image.Image ): A = 1 elif isinstance(_lowerCAmelCase , torch.Tensor ): A = image.shape[0] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): A = len(_lowerCAmelCase ) else: raise ValueError( F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCAmelCase )}""" ) A = self._execution_device A = batch_size * num_images_per_prompt A = guidance_scale > 1.0 A = self._encode_image(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # prior self.scheduler.set_timesteps(_lowerCAmelCase , device=_lowerCAmelCase ) A = self.scheduler.timesteps A = self.prior.config.num_embeddings A = self.prior.config.embedding_dim A = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim A = latents.reshape(latents.shape[0] , _lowerCAmelCase , _lowerCAmelCase ) for i, t in enumerate(self.progress_bar(_lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A = self.scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) A = self.prior( _lowerCAmelCase , timestep=_lowerCAmelCase , proj_embedding=_lowerCAmelCase , ).predicted_image_embedding # remove the variance A , A = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: A , A = noise_pred.chunk(2 ) A = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) A = self.scheduler.step( _lowerCAmelCase , timestep=_lowerCAmelCase , sample=_lowerCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_lowerCAmelCase ) A = [] for i, latent in enumerate(_lowerCAmelCase ): print() A = self.renderer.decode( latent[None, :] , _lowerCAmelCase , size=_lowerCAmelCase , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_lowerCAmelCase ) A = torch.stack(_lowerCAmelCase ) if output_type not in ["np", "pil"]: raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) A = images.cpu().numpy() if output_type == "pil": A = [self.numpy_to_pil(_lowerCAmelCase ) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_lowerCAmelCase )
258
0
'''simple docstring''' import math def _UpperCamelCase ( __A ) -> 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 _UpperCamelCase ( __A = 0.1 ) -> int: '''simple docstring''' UpperCamelCase__ = 3 UpperCamelCase__ = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ): primes += is_prime(__A ) j += 2 return j if __name__ == "__main__": import doctest doctest.testmod()
80
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class __UpperCAmelCase : '''simple docstring''' def __init__(self : Union[str, Any] , _lowerCAmelCase : Optional[int]=None , **_lowerCAmelCase : Union[str, Any] ): logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) A = model A = kwargs.get("""model_save_dir""" , _lowerCAmelCase ) A = kwargs.get("""latest_model_name""" , _lowerCAmelCase ) def __call__(self : Tuple , **_lowerCAmelCase : Optional[Any] ): A = {k: np.array(_lowerCAmelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCAmelCase , _lowerCAmelCase ) @staticmethod def A (_lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[Any]=None ): if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) A = """CPUExecutionProvider""" return ort.InferenceSession(_lowerCAmelCase , providers=[provider] , sess_options=_lowerCAmelCase ) def A (self : List[str] , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : List[str] ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME A = self.model_save_dir.joinpath(self.latest_model_name ) A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) A = self.model_save_dir.joinpath(_lowerCAmelCase ) if src_path.exists(): A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass def A (self : Tuple , _lowerCAmelCase : Union[str, os.PathLike] , **_lowerCAmelCase : str , ): if os.path.isfile(_lowerCAmelCase ): logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase ) # saving model weights/files self._save_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Union[bool, str, None]] = None , _lowerCAmelCase : Optional[Union[str, None]] = None , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional["ort.SessionOptions"] = None , **_lowerCAmelCase : Optional[int] , ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCAmelCase ): A = OnnxRuntimeModel.load_model( os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) A = Path(_lowerCAmelCase ) # load model from hub else: # download model A = hf_hub_download( repo_id=_lowerCAmelCase , filename=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , ) A = Path(_lowerCAmelCase ).parent A = Path(_lowerCAmelCase ).name A = OnnxRuntimeModel.load_model(_lowerCAmelCase , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) return cls(model=_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : str , ): A = None if len(str(_lowerCAmelCase ).split("""@""" ) ) == 2: A , A = model_id.split("""@""" ) return cls._from_pretrained( model_id=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , **_lowerCAmelCase , )
258
0
from collections import Counter import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split SCREAMING_SNAKE_CASE__ = datasets.load_iris() SCREAMING_SNAKE_CASE__ = np.array(data["""data"""]) SCREAMING_SNAKE_CASE__ = np.array(data["""target"""]) SCREAMING_SNAKE_CASE__ = data['target_names'] SCREAMING_SNAKE_CASE__ = train_test_split(X, y) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : str ) -> int: return np.linalg.norm(np.array(SCREAMING_SNAKE_CASE ) - np.array(SCREAMING_SNAKE_CASE ) ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Optional[int] , SCREAMING_SNAKE_CASE : Optional[int]=5 ) -> Tuple: __lowercase = zip(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) # List of distances of all points from the point to be classified __lowercase = [] for data_point in data: __lowercase = euclidean_distance(data_point[0] , SCREAMING_SNAKE_CASE ) distances.append((distance, data_point[1]) ) # Choosing 'k' points with the least distances. __lowercase = [i[1] for i in sorted(SCREAMING_SNAKE_CASE )[:k]] # Most commonly occurring class among them # is the class into which the point is classified __lowercase = Counter(SCREAMING_SNAKE_CASE ).most_common(1 )[0][0] return classes[result] if __name__ == "__main__": print(classifier(X_train, y_train, classes, [4.4, 3.1, 1.3, 1.4]))
325
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def A (self : str , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : str ): A = hf_hub_download( repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) A = VideoClassificationPipeline(model=_lowerCAmelCase , image_processor=_lowerCAmelCase , top_k=2 ) A = [ example_video_filepath, """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""", ] return video_classifier, examples def A (self : Optional[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[Any] ): for example in examples: A = video_classifier(_lowerCAmelCase ) self.assertEqual( _lowerCAmelCase , [ {"""score""": ANY(_lowerCAmelCase ), """label""": ANY(_lowerCAmelCase )}, {"""score""": ANY(_lowerCAmelCase ), """label""": ANY(_lowerCAmelCase )}, ] , ) @require_torch def A (self : Optional[Any] ): A = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification""" A = VideoMAEFeatureExtractor( size={"""shortest_edge""": 10} , crop_size={"""height""": 10, """width""": 10} ) A = pipeline( """video-classification""" , model=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , frame_sampling_rate=4 ) A = hf_hub_download(repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) A = video_classifier(_lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}] , ) A = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}], [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}], ] , ) @require_tf def A (self : List[Any] ): pass
258
0
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class __lowerCAmelCase ( unittest.TestCase ): def snake_case ( self ): """simple docstring""" if self.framework == "pytorch": subprocess.run( F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding="""utf-8""" , check=_lowerCAmelCase , ) assert hasattr(self , """env""" ) def snake_case ( self , _snake_case=1 ): """simple docstring""" return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'{self.env.base_job_name}-single' , instance_count=_lowerCAmelCase , instance_type=self.instance_type , debugger_hook_config=_lowerCAmelCase , hyperparameters={**self.env.hyperparameters, """model_name_or_path""": self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version="""py36""" , ) def snake_case ( self , _snake_case ): """simple docstring""" TrainingJobAnalytics(_lowerCAmelCase ).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv' ) def snake_case ( self ): """simple docstring""" _lowerCAmelCase = self.create_estimator() # run training estimator.fit() # result dataframe _lowerCAmelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis _lowerCAmelCase = list(result_metrics_df[result_metrics_df.metric_name == """eval_accuracy"""]["""value"""] ) _lowerCAmelCase = list(result_metrics_df[result_metrics_df.metric_name == """eval_loss"""]["""value"""] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping _lowerCAmelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get("""TrainingTimeInSeconds""" , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["""eval_accuracy"""] for t in eval_accuracy ) assert all(t <= self.results["""eval_loss"""] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'{estimator.latest_training_job.name}.json' , """w""" ) as outfile: json.dump({"""train_time""": train_runtime, """eval_accuracy""": eval_accuracy, """eval_loss""": eval_loss} , _lowerCAmelCase )
82
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _lowerCamelCase : int = 10 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" for i in range(UpperCAmelCase , UpperCAmelCase ): if array[i] == target: return i return -1 def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" A = 0 A = len(UpperCAmelCase ) while left <= right: if right - left < precision: return lin_search(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) A = (left + right) // 3 + 1 A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: A = one_third - 1 elif array[two_third] < target: A = two_third + 1 else: A = one_third + 1 A = two_third - 1 else: return -1 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if left < right: if right - left < precision: return lin_search(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) A = (left + right) // 3 + 1 A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(UpperCAmelCase , one_third - 1 , UpperCAmelCase , UpperCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , UpperCAmelCase , UpperCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase : str = input('Enter numbers separated by comma:\n').strip() _lowerCamelCase : str = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." _lowerCamelCase : Optional[int] = int(input('Enter the number to be found in the list:\n').strip()) _lowerCamelCase : Union[str, Any] = ite_ternary_search(collection, target) _lowerCamelCase : Union[str, Any] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"Iterative search: {target} found at positions: {resulta}") print(f"Recursive search: {target} found at positions: {resulta}") else: print('Not found')
258
0
import datasets from .evaluate import evaluate __UpperCamelCase : List[str] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' __UpperCamelCase : List[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' __UpperCamelCase : Dict = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE( datasets.Metric ): def lowerCAmelCase_ ( self: int ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': { 'id': datasets.Value('string' ), 'prediction_text': datasets.features.Sequence(datasets.Value('string' ) ), }, 'references': { 'id': datasets.Value('string' ), 'answers': datasets.features.Sequence( { 'text': datasets.Value('string' ), 'answer_start': datasets.Value('int32' ), } ), }, } ) , codebase_urls=['https://www.atticusprojectai.org/cuad'] , reference_urls=['https://www.atticusprojectai.org/cuad'] , ) def lowerCAmelCase_ ( self: Dict , UpperCamelCase: Optional[Any] , UpperCamelCase: Any ) -> Optional[Any]: snake_case__ = {prediction['id']: prediction['prediction_text'] for prediction in predictions} snake_case__ = [ { 'paragraphs': [ { 'qas': [ { 'answers': [{'text': answer_text} for answer_text in ref['answers']['text']], 'id': ref['id'], } for ref in references ] } ] } ] snake_case__ = evaluate(dataset=_lowerCAmelCase , predictions=_lowerCAmelCase ) return score
307
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = CycleDiffusionPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } __lowerCAmelCase = PipelineTesterMixin.required_optional_params - {'''latents'''} __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def A (self : int ): torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) A = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , num_train_timesteps=1000 , clip_sample=_lowerCAmelCase , set_alpha_to_one=_lowerCAmelCase , ) torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) A = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) A = CLIPTextModel(_lowerCAmelCase ) A = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def A (self : Dict , _lowerCAmelCase : str , _lowerCAmelCase : List[str]=0 ): A = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) A = image / 2 + 0.5 if str(_lowerCAmelCase ).startswith("""mps""" ): A = torch.manual_seed(_lowerCAmelCase ) else: A = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) A = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def A (self : Any ): A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = CycleDiffusionPipeline(**_lowerCAmelCase ) A = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) A = self.get_dummy_inputs(_lowerCAmelCase ) A = pipe(**_lowerCAmelCase ) A = output.images A = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) A = np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def A (self : str ): A = self.get_dummy_components() for name, module in components.items(): if hasattr(_lowerCAmelCase , """half""" ): A = module.half() A = CycleDiffusionPipeline(**_lowerCAmelCase ) A = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) A = self.get_dummy_inputs(_lowerCAmelCase ) A = pipe(**_lowerCAmelCase ) A = output.images A = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) A = np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A (self : Optional[int] ): return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def A (self : Optional[Any] ): return super().test_inference_batch_single_identical() @skip_mps def A (self : Dict ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def A (self : Optional[Any] ): return super().test_save_load_optional_components() @skip_mps def A (self : Optional[int] ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A (self : int ): A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) A = init_image.resize((512, 512) ) A = """CompVis/stable-diffusion-v1-4""" A = DDIMScheduler.from_pretrained(_lowerCAmelCase , subfolder="""scheduler""" ) A = CycleDiffusionPipeline.from_pretrained( _lowerCAmelCase , scheduler=_lowerCAmelCase , safety_checker=_lowerCAmelCase , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() A = """A black colored car""" A = """A blue colored car""" A = torch.manual_seed(0 ) A = pipe( prompt=_lowerCAmelCase , source_prompt=_lowerCAmelCase , image=_lowerCAmelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCAmelCase , output_type="""np""" , ) A = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def A (self : int ): A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) A = init_image.resize((512, 512) ) A = """CompVis/stable-diffusion-v1-4""" A = DDIMScheduler.from_pretrained(_lowerCAmelCase , subfolder="""scheduler""" ) A = CycleDiffusionPipeline.from_pretrained(_lowerCAmelCase , scheduler=_lowerCAmelCase , safety_checker=_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() A = """A black colored car""" A = """A blue colored car""" A = torch.manual_seed(0 ) A = pipe( prompt=_lowerCAmelCase , source_prompt=_lowerCAmelCase , image=_lowerCAmelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCAmelCase , output_type="""np""" , ) A = output.images assert np.abs(image - expected_image ).max() < 2e-2
258
0
import copy import random from transformers import CLIPTokenizer class __snake_case ( A__ ): def __init__( self ,*snake_case ,**snake_case ): '''simple docstring''' super().__init__(*_lowerCAmelCase ,**_lowerCAmelCase ) lowercase : Optional[Any] = {} def _SCREAMING_SNAKE_CASE ( self ,snake_case ,*snake_case ,**snake_case ): '''simple docstring''' lowercase : int = super().add_tokens(_lowerCAmelCase ,*_lowerCAmelCase ,**_lowerCAmelCase ) if num_added_tokens == 0: raise ValueError( f"The tokenizer already contains the token {placeholder_token}. Please pass a different" """ `placeholder_token` that is not already in the tokenizer.""" ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,*snake_case ,snake_case=1 ,**snake_case ): '''simple docstring''' lowercase : List[str] = [] if num_vec_per_token == 1: self.try_adding_tokens(_lowerCAmelCase ,*_lowerCAmelCase ,**_lowerCAmelCase ) output.append(_lowerCAmelCase ) else: lowercase : List[str] = [] for i in range(_lowerCAmelCase ): lowercase : Dict = placeholder_token + f"_{i}" self.try_adding_tokens(_lowerCAmelCase ,*_lowerCAmelCase ,**_lowerCAmelCase ) output.append(_lowerCAmelCase ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( f"The tokenizer already has placeholder token {token} that can get confused with" f" {placeholder_token}keep placeholder tokens independent" ) lowercase : str = output def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case=False ,snake_case=1.0 ): '''simple docstring''' if isinstance(_lowerCAmelCase ,_lowerCAmelCase ): lowercase : Union[str, Any] = [] for i in range(len(_lowerCAmelCase ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] ,vector_shuffle=_lowerCAmelCase ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: lowercase : str = self.token_map[placeholder_token] lowercase : Union[str, Any] = tokens[: 1 + int(len(_lowerCAmelCase ) * prop_tokens_to_load )] if vector_shuffle: lowercase : Dict = copy.copy(_lowerCAmelCase ) random.shuffle(_lowerCAmelCase ) lowercase : Any = text.replace(_lowerCAmelCase ,""" """.join(_lowerCAmelCase ) ) return text def __call__( self ,snake_case ,*snake_case ,snake_case=False ,snake_case=1.0 ,**snake_case ): '''simple docstring''' return super().__call__( self.replace_placeholder_tokens_in_text( _lowerCAmelCase ,vector_shuffle=_lowerCAmelCase ,prop_tokens_to_load=_lowerCAmelCase ) ,*_lowerCAmelCase ,**_lowerCAmelCase ,) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,*snake_case ,snake_case=False ,snake_case=1.0 ,**snake_case ): '''simple docstring''' return super().encode( self.replace_placeholder_tokens_in_text( _lowerCAmelCase ,vector_shuffle=_lowerCAmelCase ,prop_tokens_to_load=_lowerCAmelCase ) ,*_lowerCAmelCase ,**_lowerCAmelCase ,)
20
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(A__ ) class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : Tuple , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : List[str] ): super().__init__(*_lowerCAmelCase , **_lowerCAmelCase ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == """tf""" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def A (self : Any , _lowerCAmelCase : str=None ): A = {} if top_k is not None: A = top_k return {}, {}, postprocess_params def __call__(self : str , _lowerCAmelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] , **_lowerCAmelCase : int ): return super().__call__(_lowerCAmelCase , **_lowerCAmelCase ) def A (self : List[str] , _lowerCAmelCase : List[Any] ): A = load_image(_lowerCAmelCase ) A = self.image_processor(images=_lowerCAmelCase , return_tensors=self.framework ) return model_inputs def A (self : Union[str, Any] , _lowerCAmelCase : Optional[int] ): A = self.model(**_lowerCAmelCase ) return model_outputs def A (self : Optional[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=5 ): if top_k > self.model.config.num_labels: A = self.model.config.num_labels if self.framework == "pt": A = model_outputs.logits.softmax(-1 )[0] A , A = probs.topk(_lowerCAmelCase ) elif self.framework == "tf": A = stable_softmax(model_outputs.logits , axis=-1 )[0] A = tf.math.top_k(_lowerCAmelCase , k=_lowerCAmelCase ) A , A = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) A = scores.tolist() A = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCAmelCase , _lowerCAmelCase )]
258
0
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration UpperCAmelCase__ : Optional[Any] = 500000 UpperCAmelCase__ : Optional[Any] = os.path.split(__file__) UpperCAmelCase__ : Tuple = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def lowerCamelCase__ ( a , **a ) -> Dict: _A: Optional[Any] = dataset.map(**a ) @get_duration def lowerCamelCase__ ( a , **a ) -> List[str]: _A: Any = dataset.filter(**a ) def lowerCamelCase__ ( ) -> Tuple: _A: str = {'''num examples''': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: _A: Any = datasets.Features({'''text''': datasets.Value('''string''' ), '''numbers''': datasets.Value('''float32''' )} ) _A: List[Any] = generate_example_dataset( os.path.join(a , '''dataset.arrow''' ) , a , num_examples=a ) _A: Optional[int] = transformers.AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=a ) def tokenize(a ): return tokenizer(examples['''text'''] ) _A: List[str] = map(a ) _A: str = map(a , batched=a ) _A: int = map(a , function=lambda a : None , batched=a ) with dataset.formatted_as(type='''numpy''' ): _A: int = map(a , function=lambda a : None , batched=a ) with dataset.formatted_as(type='''pandas''' ): _A: Union[str, Any] = map(a , function=lambda a : None , batched=a ) with dataset.formatted_as(type='''torch''' , columns='''numbers''' ): _A: Optional[int] = map(a , function=lambda a : None , batched=a ) with dataset.formatted_as(type='''tensorflow''' , columns='''numbers''' ): _A: Dict = map(a , function=lambda a : None , batched=a ) _A: Any = map(a , function=a , batched=a ) _A: Optional[Any] = filter(a ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(a , '''wb''' ) as f: f.write(json.dumps(a ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
121
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
258
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A ={ 'configuration_rag': ['RagConfig'], 'retrieval_rag': ['RagRetriever'], 'tokenization_rag': ['RagTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ 'RagModel', 'RagPreTrainedModel', 'RagSequenceForGeneration', 'RagTokenForGeneration', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ 'TFRagModel', 'TFRagPreTrainedModel', 'TFRagSequenceForGeneration', 'TFRagTokenForGeneration', ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys __A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
163
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __UpperCAmelCase ( A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = BioGptTokenizer __lowerCAmelCase = False def A (self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] A = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) A = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(_lowerCAmelCase ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(_lowerCAmelCase ) ) def A (self : Tuple , _lowerCAmelCase : List[str] ): A = """lower newer""" A = """lower newer""" return input_text, output_text def A (self : List[Any] ): A = BioGptTokenizer(self.vocab_file , self.merges_file ) A = """lower""" A = ["""low""", """er</w>"""] A = tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) A = tokens + ["""<unk>"""] A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , _lowerCAmelCase ) @slow def A (self : Union[str, Any] ): A = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A = tokenizer.encode("""sequence builders""" , add_special_tokens=_lowerCAmelCase ) A = tokenizer.encode("""multi-sequence build""" , add_special_tokens=_lowerCAmelCase ) A = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) A = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
258
0
'''simple docstring''' from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class lowercase ( A__ ): """simple docstring""" def __lt__( self ,a_ ) -> int: return self[-1] < other[-1] def __eq__( self ,a_ ) -> Optional[int]: return self[-1] == other[-1] def snake_case_ ( lowerCAmelCase_ )-> list: '''simple docstring''' _UpperCAmelCase : List[Any] = [] # sort into stacks for element in collection: _UpperCAmelCase : Tuple = Stack([element] ) _UpperCAmelCase : Tuple = bisect_left(lowerCAmelCase_ , lowerCAmelCase_ ) if i != len(lowerCAmelCase_ ): stacks[i].append(lowerCAmelCase_ ) else: stacks.append(lowerCAmelCase_ ) # use a heap-based merge to merge stack efficiently _UpperCAmelCase : List[str] = merge(*(reversed(lowerCAmelCase_ ) for stack in stacks) ) return collection if __name__ == "__main__": A_ : Union[str, Any] = input("""Enter numbers separated by a comma:\n""").strip() A_ : List[str] = [int(item) for item in user_input.split(""",""")] print(patience_sort(unsorted))
215
'''simple docstring''' from __future__ import annotations import numpy as np def __a ( UpperCAmelCase ) ->Optional[int]: """simple docstring""" return np.maximum(0 , UpperCAmelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
258
0
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A ( A__ ): UpperCamelCase_ : str =(CMStochasticIterativeScheduler,) UpperCamelCase_ : Any =10 def _A (self , **lowerCAmelCase ): __lowercase= { 'num_train_timesteps': 2_0_1, 'sigma_min': 0.0_02, 'sigma_max': 80.0, } config.update(**_lowerCAmelCase ) return config def _A (self ): __lowercase= 1_0 __lowercase= self.get_scheduler_config() __lowercase= self.scheduler_classes[0](**_lowerCAmelCase ) scheduler.set_timesteps(_lowerCAmelCase ) __lowercase= scheduler.timesteps[0] __lowercase= scheduler.timesteps[1] __lowercase= self.dummy_sample __lowercase= 0.1 * sample __lowercase= scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ).prev_sample __lowercase= scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _A (self ): for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_lowerCAmelCase ) def _A (self ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=_lowerCAmelCase ) def _A (self ): __lowercase= self.scheduler_classes[0] __lowercase= self.get_scheduler_config() __lowercase= scheduler_class(**_lowerCAmelCase ) __lowercase= 1 scheduler.set_timesteps(_lowerCAmelCase ) __lowercase= scheduler.timesteps __lowercase= torch.manual_seed(0 ) __lowercase= self.dummy_model() __lowercase= self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(_lowerCAmelCase ): # 1. scale model input __lowercase= scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) # 2. predict noise residual __lowercase= model(_lowerCAmelCase , _lowerCAmelCase ) # 3. predict previous sample x_t-1 __lowercase= scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ).prev_sample __lowercase= pred_prev_sample __lowercase= torch.sum(torch.abs(_lowerCAmelCase ) ) __lowercase= torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 1_92.76_14 ) < 1E-2 assert abs(result_mean.item() - 0.25_10 ) < 1E-3 def _A (self ): __lowercase= self.scheduler_classes[0] __lowercase= self.get_scheduler_config() __lowercase= scheduler_class(**_lowerCAmelCase ) __lowercase= [1_0_6, 0] scheduler.set_timesteps(timesteps=_lowerCAmelCase ) __lowercase= scheduler.timesteps __lowercase= torch.manual_seed(0 ) __lowercase= self.dummy_model() __lowercase= self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowercase= scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) # 2. predict noise residual __lowercase= model(_lowerCAmelCase , _lowerCAmelCase ) # 3. predict previous sample x_t-1 __lowercase= scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ).prev_sample __lowercase= pred_prev_sample __lowercase= torch.sum(torch.abs(_lowerCAmelCase ) ) __lowercase= torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 3_47.63_57 ) < 1E-2 assert abs(result_mean.item() - 0.45_27 ) < 1E-3 def _A (self ): __lowercase= self.scheduler_classes[0] __lowercase= self.get_scheduler_config() __lowercase= scheduler_class(**_lowerCAmelCase ) __lowercase= [3_9, 3_0, 1_2, 1_5, 0] with self.assertRaises(_lowerCAmelCase , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=_lowerCAmelCase ) def _A (self ): __lowercase= self.scheduler_classes[0] __lowercase= self.get_scheduler_config() __lowercase= scheduler_class(**_lowerCAmelCase ) __lowercase= [3_9, 3_0, 1_2, 1, 0] __lowercase= len(_lowerCAmelCase ) with self.assertRaises(_lowerCAmelCase , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=_lowerCAmelCase , timesteps=_lowerCAmelCase ) def _A (self ): __lowercase= self.scheduler_classes[0] __lowercase= self.get_scheduler_config() __lowercase= scheduler_class(**_lowerCAmelCase ) __lowercase= [scheduler.config.num_train_timesteps] with self.assertRaises( _lowerCAmelCase , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=_lowerCAmelCase )
295
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCAmelCase : '''simple docstring''' def __init__(self : Tuple , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=13 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : Dict=2 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Dict=16 , _lowerCAmelCase : str=[1, 2, 1] , _lowerCAmelCase : List[Any]=[2, 2, 4] , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Any=2.0 , _lowerCAmelCase : Any=True , _lowerCAmelCase : int=0.0 , _lowerCAmelCase : List[Any]=0.0 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : List[str]="gelu" , _lowerCAmelCase : Optional[Any]=False , _lowerCAmelCase : str=True , _lowerCAmelCase : List[str]=0.02 , _lowerCAmelCase : Dict=1e-5 , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=None , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=10 , _lowerCAmelCase : int=8 , ): A = parent A = batch_size A = image_size A = patch_size A = num_channels A = embed_dim A = depths A = num_heads A = window_size A = mlp_ratio A = qkv_bias A = hidden_dropout_prob A = attention_probs_dropout_prob A = drop_path_rate A = hidden_act A = use_absolute_embeddings A = patch_norm A = layer_norm_eps A = initializer_range A = is_training A = scope A = use_labels A = type_sequence_label_size A = encoder_stride def A (self : Dict ): A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A = None if self.use_labels: A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A = self.get_config() return config, pixel_values, labels def A (self : Optional[Any] ): return SwinvaConfig( 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 , ) def A (self : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] ): A = SwinvaModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) A = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A = 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 A (self : Tuple , _lowerCAmelCase : Dict , _lowerCAmelCase : int , _lowerCAmelCase : Optional[int] ): A = SwinvaForMaskedImageModeling(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A = 1 A = SwinvaForMaskedImageModeling(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def A (self : List[str] , _lowerCAmelCase : Any , _lowerCAmelCase : Dict , _lowerCAmelCase : Any ): A = self.type_sequence_label_size A = SwinvaForImageClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A (self : Union[str, Any] ): A = self.prepare_config_and_inputs() A , A , A = config_and_inputs A = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __lowerCAmelCase = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def A (self : Any ): A = SwinvaModelTester(self ) A = ConfigTester(self , config_class=_lowerCAmelCase , embed_dim=37 ) def A (self : Dict ): 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 A (self : int ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def A (self : Dict ): pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def A (self : Optional[int] ): pass def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) ) def A (self : Optional[int] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A = [*signature.parameters.keys()] A = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def A (self : int ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = True for model_class in self.all_model_classes: A = True A = False A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions A = len(self.model_tester.depths ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] A = True A = config.window_size**2 A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) A = len(_lowerCAmelCase ) # Check attention is always last and order is fine A = True A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): A = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A = 2 self.assertEqual(out_len + added_hidden_states , len(_lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def A (self : List[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] ): A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.hidden_states A = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # Swinv2 has a different seq_length A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = (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] , ) A = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) A , A , A , A = reshaped_hidden_states[0].shape A = ( reshaped_hidden_states[0].view(_lowerCAmelCase , _lowerCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A (self : Tuple ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ( 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: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = ( 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) ) A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) def A (self : Optional[int] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase ) def A (self : Union[str, Any] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def A (self : Optional[Any] ): for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = SwinvaModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def A (self : Optional[Any] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = _config_zero_init(_lowerCAmelCase ) for model_class in self.all_model_classes: A = model_class(config=_lowerCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def A (self : List[str] ): return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def A (self : List[str] ): A = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( _lowerCAmelCase ) A = self.default_image_processor A = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) A = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): A = model(**_lowerCAmelCase ) # verify the logits A = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) A = torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 ) )
258
0
import math from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import SchedulerMixin, SchedulerOutput class lowerCamelCase (A__ , A__ ): """simple docstring""" lowerCamelCase__ = 1 @register_to_config def __init__( self : Any , __magic_name__ : int = 1_000 , __magic_name__ : Optional[Union[np.ndarray, List[float]]] = None ) -> Tuple: # set `betas`, `alphas`, `timesteps` self.set_timesteps(_lowerCAmelCase ) # standard deviation of the initial noise distribution SCREAMING_SNAKE_CASE_ = 1.0 # For now we only support F-PNDM, i.e. the runge-kutta method # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf # mainly at formula (9), (12), (13) and the Algorithm 2. SCREAMING_SNAKE_CASE_ = 4 # running values SCREAMING_SNAKE_CASE_ = [] def __A ( self : Dict , __magic_name__ : int , __magic_name__ : Union[str, torch.device] = None ) -> List[str]: SCREAMING_SNAKE_CASE_ = num_inference_steps SCREAMING_SNAKE_CASE_ = torch.linspace(1 , 0 , num_inference_steps + 1 )[:-1] SCREAMING_SNAKE_CASE_ = torch.cat([steps, torch.tensor([0.0] )] ) if self.config.trained_betas is not None: SCREAMING_SNAKE_CASE_ = torch.tensor(self.config.trained_betas , dtype=torch.floataa ) else: SCREAMING_SNAKE_CASE_ = torch.sin(steps * math.pi / 2 ) ** 2 SCREAMING_SNAKE_CASE_ = (1.0 - self.betas**2) ** 0.5 SCREAMING_SNAKE_CASE_ = (torch.atana(self.betas , self.alphas ) / math.pi * 2)[:-1] SCREAMING_SNAKE_CASE_ = timesteps.to(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = [] def __A ( self : Any , __magic_name__ : torch.FloatTensor , __magic_name__ : int , __magic_name__ : torch.FloatTensor , __magic_name__ : bool = True , ) -> Dict: if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) SCREAMING_SNAKE_CASE_ = (self.timesteps == timestep).nonzero().item() SCREAMING_SNAKE_CASE_ = timestep_index + 1 SCREAMING_SNAKE_CASE_ = sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index] self.ets.append(_lowerCAmelCase ) if len(self.ets ) == 1: SCREAMING_SNAKE_CASE_ = self.ets[-1] elif len(self.ets ) == 2: SCREAMING_SNAKE_CASE_ = (3 * self.ets[-1] - self.ets[-2]) / 2 elif len(self.ets ) == 3: SCREAMING_SNAKE_CASE_ = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 else: SCREAMING_SNAKE_CASE_ = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4]) SCREAMING_SNAKE_CASE_ = self._get_prev_sample(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=_lowerCAmelCase ) def __A ( self : int , __magic_name__ : torch.FloatTensor , *__magic_name__ : Union[str, Any] , **__magic_name__ : List[str] ) -> Dict: return sample def __A ( self : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] ) -> Optional[Any]: SCREAMING_SNAKE_CASE_ = self.alphas[timestep_index] SCREAMING_SNAKE_CASE_ = self.betas[timestep_index] SCREAMING_SNAKE_CASE_ = self.alphas[prev_timestep_index] SCREAMING_SNAKE_CASE_ = self.betas[prev_timestep_index] SCREAMING_SNAKE_CASE_ = (sample - sigma * ets) / max(_lowerCAmelCase , 1e-8 ) SCREAMING_SNAKE_CASE_ = next_alpha * pred + ets * next_sigma return prev_sample def __len__( self : Union[str, Any] ) -> Tuple: return self.config.num_train_timesteps
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" def get_matched_characters(UpperCAmelCase , UpperCAmelCase ) -> str: A = [] A = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): A = int(max(0 , i - limit ) ) A = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(UpperCAmelCase ) A = f"""{_stra[0:_stra.index(UpperCAmelCase )]} {_stra[_stra.index(UpperCAmelCase ) + 1:]}""" return "".join(UpperCAmelCase ) # matching characters A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = len(UpperCAmelCase ) # transposition A = ( len([(ca, ca) for ca, ca in zip(UpperCAmelCase , UpperCAmelCase ) if ca != ca] ) // 2 ) if not match_count: A = 0.0 else: A = ( 1 / 3 * ( match_count / len(UpperCAmelCase ) + match_count / len(UpperCAmelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
258
0
import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py _SCREAMING_SNAKE_CASE = 'src/diffusers' _SCREAMING_SNAKE_CASE = '.' # This is to make sure the diffusers module imported is the one in the repo. _SCREAMING_SNAKE_CASE = importlib.util.spec_from_file_location( 'diffusers', os.path.join(DIFFUSERS_PATH, '__init__.py'), submodule_search_locations=[DIFFUSERS_PATH], ) _SCREAMING_SNAKE_CASE = spec.loader.load_module() def snake_case ( snake_case__ :str , snake_case__ :str) -> List[str]: return line.startswith(snake_case__) or len(snake_case__) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""" , snake_case__) is not None def snake_case ( snake_case__ :Optional[Any]) -> Any: _A = object_name.split(""".""") _A = 0 # First let's find the module where our object lives. _A = parts[i] while i < len(snake_case__) and not os.path.isfile(os.path.join(snake_case__ , F'''{module}.py''')): i += 1 if i < len(snake_case__): _A = os.path.join(snake_case__ , parts[i]) if i >= len(snake_case__): raise ValueError(F'''`object_name` should begin with the name of a module of diffusers but got {object_name}.''') with open(os.path.join(snake_case__ , F'''{module}.py''') , """r""" , encoding="""utf-8""" , newline="""\n""") as f: _A = f.readlines() # Now let's find the class / func in the code! _A = """""" _A = 0 for name in parts[i + 1 :]: while ( line_index < len(snake_case__) and re.search(RF'''^{indent}(class|def)\s+{name}(\(|\:)''' , lines[line_index]) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(snake_case__): raise ValueError(F''' {object_name} does not match any function or class in {module}.''') # We found the beginning of the class / func, now let's find the end (when the indent diminishes). _A = line_index while line_index < len(snake_case__) and _should_continue(lines[line_index] , snake_case__): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1]) <= 1: line_index -= 1 _A = lines[start_index:line_index] return "".join(snake_case__) _SCREAMING_SNAKE_CASE = re.compile(R'^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)') _SCREAMING_SNAKE_CASE = re.compile(R'^\s*(\S+)->(\S+)(\s+.*|$)') _SCREAMING_SNAKE_CASE = re.compile(R'<FILL\s+[^>]*>') def snake_case ( snake_case__ :Optional[int]) -> List[str]: _A = code.split("""\n""") _A = 0 while idx < len(snake_case__) and len(lines[idx]) == 0: idx += 1 if idx < len(snake_case__): return re.search(R"""^(\s*)\S""" , lines[idx]).groups()[0] return "" def snake_case ( snake_case__ :Optional[int]) -> Any: _A = len(get_indent(snake_case__)) > 0 if has_indent: _A = F'''class Bla:\n{code}''' _A = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=snake_case__) _A = black.format_str(snake_case__ , mode=snake_case__) _A , _A = style_docstrings_in_code(snake_case__) return result[len("""class Bla:\n""") :] if has_indent else result def snake_case ( snake_case__ :Dict , snake_case__ :Optional[Any]=False) -> List[Any]: with open(snake_case__ , """r""" , encoding="""utf-8""" , newline="""\n""") as f: _A = f.readlines() _A = [] _A = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(snake_case__): _A = _re_copy_warning.search(lines[line_index]) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. _A , _A , _A = search.groups() _A = find_code_in_diffusers(snake_case__) _A = get_indent(snake_case__) _A = line_index + 1 if indent == theoretical_indent else line_index + 2 _A = theoretical_indent _A = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. _A = True while line_index < len(snake_case__) and should_continue: line_index += 1 if line_index >= len(snake_case__): break _A = lines[line_index] _A = _should_continue(snake_case__ , snake_case__) and re.search(F'''^{indent}# End copy''' , snake_case__) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1]) <= 1: line_index -= 1 _A = lines[start_index:line_index] _A = """""".join(snake_case__) # Remove any nested `Copied from` comments to avoid circular copies _A = [line for line in theoretical_code.split("""\n""") if _re_copy_warning.search(snake_case__) is None] _A = """\n""".join(snake_case__) # Before comparing, use the `replace_pattern` on the original code. if len(snake_case__) > 0: _A = replace_pattern.replace("""with""" , """""").split(""",""") _A = [_re_replace_pattern.search(snake_case__) for p in patterns] for pattern in patterns: if pattern is None: continue _A , _A , _A = pattern.groups() _A = re.sub(snake_case__ , snake_case__ , snake_case__) if option.strip() == "all-casing": _A = re.sub(obja.lower() , obja.lower() , snake_case__) _A = re.sub(obja.upper() , obja.upper() , snake_case__) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line _A = blackify(lines[start_index - 1] + theoretical_code) _A = theoretical_code[len(lines[start_index - 1]) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index]) if overwrite: _A = lines[:start_index] + [theoretical_code] + lines[line_index:] _A = start_index + 1 if overwrite and len(snake_case__) > 0: # Warn the user a file has been modified. print(F'''Detected changes, rewriting {filename}.''') with open(snake_case__ , """w""" , encoding="""utf-8""" , newline="""\n""") as f: f.writelines(snake_case__) return diffs def snake_case ( snake_case__ :Union[str, Any] = False) -> Optional[Any]: _A = glob.glob(os.path.join(snake_case__ , """**/*.py""") , recursive=snake_case__) _A = [] for filename in all_files: _A = is_copy_consistent(snake_case__ , snake_case__) diffs += [F'''- {filename}: copy does not match {d[0]} at line {d[1]}''' for d in new_diffs] if not overwrite and len(snake_case__) > 0: _A = """\n""".join(snake_case__) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""") if __name__ == "__main__": _SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.') _SCREAMING_SNAKE_CASE = parser.parse_args() check_copies(args.fix_and_overwrite)
180
'''simple docstring''' import datasets from .evaluate import evaluate _lowerCamelCase : List[str] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' _lowerCamelCase : List[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' _lowerCamelCase : Dict = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def A (self : int ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def A (self : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ): A = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} A = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] A = evaluate(dataset=_lowerCAmelCase , predictions=_lowerCAmelCase ) return score
258
0
'''simple docstring''' from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig a__ : List[Any] = { 'susnato/ernie-m-base_pytorch': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json', 'susnato/ernie-m-large_pytorch': 'https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json', } class lowercase_ ( A__ ): __UpperCAmelCase = 'ernie_m' __UpperCAmelCase = {'dropout': 'classifier_dropout', 'num_classes': 'num_labels'} def __init__( self , a = 25_00_02 , a = 7_68 , a = 12 , a = 12 , a = 30_72 , a = "gelu" , a = 0.1 , a = 0.1 , a = 5_14 , a = 0.02 , a = 1 , a = 1e-05 , a=None , a=False , a=0.0 , **a , ): super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) 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__ = initializer_range UpperCamelCase__ = layer_norm_eps UpperCamelCase__ = classifier_dropout UpperCamelCase__ = is_decoder UpperCamelCase__ = act_dropout
80
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __lowerCAmelCase = None class __UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __lowerCAmelCase = PandasConfig def A (self : Tuple ): return datasets.DatasetInfo(features=self.config.features ) def A (self : Optional[int] , _lowerCAmelCase : List[Any] ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCAmelCase , (str, list, tuple) ): A = data_files if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A = [] for split_name, files in data_files.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCAmelCase , gen_kwargs={"""files""": files} ) ) return splits def A (self : Dict , _lowerCAmelCase : pa.Table ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example A = table_cast(_lowerCAmelCase , self.config.features.arrow_schema ) return pa_table def A (self : List[Any] , _lowerCAmelCase : Optional[Any] ): for i, file in enumerate(itertools.chain.from_iterable(_lowerCAmelCase ) ): with open(_lowerCAmelCase , """rb""" ) as f: A = pa.Table.from_pandas(pd.read_pickle(_lowerCAmelCase ) ) yield i, self._cast_table(_lowerCAmelCase )
258
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available SCREAMING_SNAKE_CASE__ = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys SCREAMING_SNAKE_CASE__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
325
'''simple docstring''' from collections import Counter from timeit import timeit def __a ( UpperCAmelCase = "" , ) ->bool: """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def __a ( UpperCAmelCase = "" ) ->bool: """simple docstring""" if len(UpperCAmelCase ) == 0: return True A = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string A = {} for character in lower_case_input_str: A = character_freq_dict.get(UpperCAmelCase , 0 ) + 1 A = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __a ( UpperCAmelCase = "" ) ->None: """simple docstring""" print("""\nFor string = """ , UpperCAmelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": _lowerCamelCase : Any = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) _lowerCamelCase : Any = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
258
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A__ = { 'configuration_luke': ['LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LukeConfig'], 'tokenization_luke': ['LukeTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ = [ 'LUKE_PRETRAINED_MODEL_ARCHIVE_LIST', 'LukeForEntityClassification', 'LukeForEntityPairClassification', 'LukeForEntitySpanClassification', 'LukeForMultipleChoice', 'LukeForQuestionAnswering', 'LukeForSequenceClassification', 'LukeForTokenClassification', 'LukeForMaskedLM', 'LukeModel', 'LukePreTrainedModel', ] if TYPE_CHECKING: from .configuration_luke import LUKE_PRETRAINED_CONFIG_ARCHIVE_MAP, LukeConfig from .tokenization_luke import LukeTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_luke import ( LUKE_PRETRAINED_MODEL_ARCHIVE_LIST, LukeForEntityClassification, LukeForEntityPairClassification, LukeForEntitySpanClassification, LukeForMaskedLM, LukeForMultipleChoice, LukeForQuestionAnswering, LukeForSequenceClassification, LukeForTokenClassification, LukeModel, LukePreTrainedModel, ) else: import sys A__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
82
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = '''encodec''' def __init__(self : List[Any] , _lowerCAmelCase : Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , _lowerCAmelCase : List[str]=2_4000 , _lowerCAmelCase : List[str]=1 , _lowerCAmelCase : List[str]=False , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : Dict=128 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : List[Any]=1 , _lowerCAmelCase : int=[8, 5, 4, 2] , _lowerCAmelCase : Any="weight_norm" , _lowerCAmelCase : List[str]=7 , _lowerCAmelCase : int=7 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : int=2 , _lowerCAmelCase : str=True , _lowerCAmelCase : str="reflect" , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Tuple=1.0 , _lowerCAmelCase : Tuple=1024 , _lowerCAmelCase : str=None , _lowerCAmelCase : Dict=True , **_lowerCAmelCase : List[str] , ): A = target_bandwidths A = sampling_rate A = audio_channels A = normalize A = chunk_length_s A = overlap A = hidden_size A = num_filters A = num_residual_layers A = upsampling_ratios A = norm_type A = kernel_size A = last_kernel_size A = residual_kernel_size A = dilation_growth_rate A = use_causal_conv A = pad_mode A = compress A = num_lstm_layers A = trim_right_ratio A = codebook_size A = codebook_dim if codebook_dim is not None else hidden_size A = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**_lowerCAmelCase ) @property def A (self : List[Any] ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def A (self : Union[str, Any] ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def A (self : Any ): A = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def A (self : List[str] ): return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
258
0
import json import os import unittest from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, require_torch from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors @require_tokenizers class __SCREAMING_SNAKE_CASE( A__ , unittest.TestCase ): _UpperCAmelCase = MvpTokenizer _UpperCAmelCase = MvpTokenizerFast _UpperCAmelCase = True _UpperCAmelCase = filter_roberta_detectors def lowerCAmelCase_ ( self: Any ) -> Any: super().setUp() snake_case__ = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] snake_case__ = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) snake_case__ = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] snake_case__ = {'unk_token': '<unk>'} snake_case__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(_lowerCAmelCase ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(_lowerCAmelCase ) ) def lowerCAmelCase_ ( self: Dict , **UpperCamelCase: int ) -> List[str]: kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def lowerCAmelCase_ ( self: Any , **UpperCamelCase: Tuple ) -> List[str]: kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def lowerCAmelCase_ ( self: Any , UpperCamelCase: str ) -> Any: return "lower newer", "lower newer" @cached_property def lowerCAmelCase_ ( self: Tuple ) -> Optional[int]: return MvpTokenizer.from_pretrained('RUCAIBox/mvp' ) @cached_property def lowerCAmelCase_ ( self: Tuple ) -> List[str]: return MvpTokenizerFast.from_pretrained('RUCAIBox/mvp' ) @require_torch def lowerCAmelCase_ ( self: Dict ) -> Optional[Any]: snake_case__ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] snake_case__ = [0, 2_50, 2_51, 1_78_18, 13, 3_91_86, 19_38, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case__ = tokenizer(_lowerCAmelCase , max_length=len(_lowerCAmelCase ) , padding=_lowerCAmelCase , return_tensors='pt' ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) snake_case__ = batch.input_ids.tolist()[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) # Test that special tokens are reset @require_torch def lowerCAmelCase_ ( self: Optional[int] ) -> Dict: snake_case__ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case__ = tokenizer(_lowerCAmelCase , padding=_lowerCAmelCase , return_tensors='pt' ) # check if input_ids are returned and no labels self.assertIn('input_ids' , _lowerCAmelCase ) self.assertIn('attention_mask' , _lowerCAmelCase ) self.assertNotIn('labels' , _lowerCAmelCase ) self.assertNotIn('decoder_attention_mask' , _lowerCAmelCase ) @require_torch def lowerCAmelCase_ ( self: int ) -> Optional[Any]: snake_case__ = [ 'Summary of the text.', 'Another summary.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case__ = tokenizer(text_target=_lowerCAmelCase , max_length=32 , padding='max_length' , return_tensors='pt' ) self.assertEqual(32 , targets['input_ids'].shape[1] ) @require_torch def lowerCAmelCase_ ( self: Optional[Any] ) -> Dict: for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case__ = tokenizer( ['I am a small frog' * 10_24, 'I am a small frog'] , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors='pt' ) self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase ) self.assertEqual(batch.input_ids.shape , (2, 10_24) ) @require_torch def lowerCAmelCase_ ( self: Optional[int] ) -> List[Any]: snake_case__ = ['A long paragraph for summarization.'] snake_case__ = [ 'Summary of the text.', ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: snake_case__ = tokenizer(_lowerCAmelCase , text_target=_lowerCAmelCase , return_tensors='pt' ) snake_case__ = inputs['input_ids'] snake_case__ = inputs['labels'] self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() ) self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() ) self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() ) def lowerCAmelCase_ ( self: List[str] ) -> List[Any]: pass def lowerCAmelCase_ ( self: str ) -> Union[str, Any]: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): snake_case__ = self.rust_tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) snake_case__ = self.tokenizer_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) snake_case__ = 'A, <mask> AllenNLP sentence.' snake_case__ = tokenizer_r.encode_plus(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase ) snake_case__ = tokenizer_p.encode_plus(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase ) # token_type_ids should put 0 everywhere self.assertEqual(sum(tokens_r['token_type_ids'] ) , sum(tokens_p['token_type_ids'] ) ) # attention_mask should put 1 everywhere, so sum over length should be 1 self.assertEqual( sum(tokens_r['attention_mask'] ) / len(tokens_r['attention_mask'] ) , sum(tokens_p['attention_mask'] ) / len(tokens_p['attention_mask'] ) , ) snake_case__ = tokenizer_r.convert_ids_to_tokens(tokens_r['input_ids'] ) snake_case__ = tokenizer_p.convert_ids_to_tokens(tokens_p['input_ids'] ) # Rust correctly handles the space before the mask while python doesnt self.assertSequenceEqual(tokens_p['input_ids'] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual(tokens_r['input_ids'] , [0, 2_50, 6, 5_02_64, 38_23, 4_87, 2_19_92, 36_45, 4, 2] ) self.assertSequenceEqual( _lowerCAmelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] ) self.assertSequenceEqual( _lowerCAmelCase , ['<s>', 'A', ',', '<mask>', 'ĠAllen', 'N', 'LP', 'Ġsentence', '.', '</s>'] )
307
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available _lowerCamelCase : Dict = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys _lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
258
0
import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class __snake_case ( unittest.TestCase , A__ ): def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = load_tool("""text-to-speech""" ) self.tool.setup() def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' torch.manual_seed(0 ) lowercase : List[str] = self.tool("""hey""" ) lowercase : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) ,) ) def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' torch.manual_seed(0 ) lowercase : Optional[Any] = self.tool("""hey""" ) lowercase : Dict = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] ,torch.tensor([-0.0_005_966_668_832_115_829, -0.0_003_657_640_190_795_064, -0.00_013_439_502_799_883_485] ) ,) )
20
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : str ): A = """ylacombe/bark-small""" A = tempfile.mkdtemp() A = """en_speaker_1""" A = """This is a test string""" A = """speaker_embeddings_path.json""" A = """speaker_embeddings""" def A (self : Optional[Any] , **_lowerCAmelCase : Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **_lowerCAmelCase ) def A (self : Dict ): shutil.rmtree(self.tmpdirname ) def A (self : Optional[Any] ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) A = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def A (self : int ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) A = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) A = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def A (self : Union[str, Any] ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) A = 35 A = 2 A = 8 A = { """semantic_prompt""": np.ones(_lowerCAmelCase ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file A = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(_lowerCAmelCase , **_lowerCAmelCase ) A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub A = processor(text=self.input_string , voice_preset=self.voice_preset ) def A (self : str ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) A = processor(text=self.input_string ) A = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
258
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Dict = [ ['attention', 'attn'], ['encoder_attention', 'encoder_attn'], ['q_lin', 'q_proj'], ['k_lin', 'k_proj'], ['v_lin', 'v_proj'], ['out_lin', 'out_proj'], ['norm_embeddings', 'layernorm_embedding'], ['position_embeddings', 'embed_positions'], ['embeddings', 'embed_tokens'], ['ffn.lin', 'fc'], ] def lowerCamelCase__ ( a ) -> List[str]: if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: _A: Any = k.replace(a , a ) if k.startswith('''encoder''' ): _A: Tuple = k.replace('''.attn''' , '''.self_attn''' ) _A: List[str] = k.replace('''norm1''' , '''self_attn_layer_norm''' ) _A: Union[str, Any] = k.replace('''norm2''' , '''final_layer_norm''' ) elif k.startswith('''decoder''' ): _A: int = k.replace('''norm1''' , '''self_attn_layer_norm''' ) _A: Tuple = k.replace('''norm2''' , '''encoder_attn_layer_norm''' ) _A: Dict = k.replace('''norm3''' , '''final_layer_norm''' ) return k def lowerCamelCase__ ( a ) -> str: _A: Optional[int] = [ '''model.encoder.layernorm_embedding.weight''', '''model.encoder.layernorm_embedding.bias''', '''model.decoder.layernorm_embedding.weight''', '''model.decoder.layernorm_embedding.bias''', ] for k in keys: _A: List[Any] = sd.pop(a ) _A: Dict = k.replace('''layernorm_embedding''' , '''layer_norm''' ) assert new_k not in sd _A: int = v UpperCAmelCase__ : Optional[int] = ['START'] @torch.no_grad() def lowerCamelCase__ ( a , a , a ) -> Optional[Any]: _A: Union[str, Any] = torch.load(a , map_location='''cpu''' ) _A: Union[str, Any] = model['''model'''] _A: Any = BlenderbotConfig.from_json_file(a ) _A: List[str] = BlenderbotForConditionalGeneration(a ) _A: Optional[int] = m.model.state_dict().keys() _A: Optional[Any] = [] _A: List[Any] = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue _A: Dict = rename_state_dict_key(a ) if new_k not in valid_keys: failures.append([k, new_k] ) else: _A: str = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(a ) m.model.load_state_dict(a , strict=a ) m.half() m.save_pretrained(a ) if __name__ == "__main__": UpperCAmelCase__ : Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--src_path', type=str, help='like blenderbot-model.bin') parser.add_argument('--save_dir', default='hf_blenderbot', type=str, help='Where to save converted model.') parser.add_argument( '--hf_config_json', default='blenderbot-3b-config.json', type=str, help='Path to config to use' ) UpperCAmelCase__ : Tuple = parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
121
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan _lowerCamelCase : List[Any] = 6_3_7_8_1_3_7.0 _lowerCamelCase : List[Any] = 6_3_5_6_7_5_2.3_1_4_2_4_5 _lowerCamelCase : Optional[int] = 637_8137 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" A = (AXIS_A - AXIS_B) / AXIS_A A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = radians(UpperCAmelCase ) A = radians(UpperCAmelCase ) # Equation A = sin((phi_a - phi_a) / 2 ) A = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda A = sqrt(sin_sq_phi + (cos(UpperCAmelCase ) * cos(UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
258
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __A ={ 'configuration_instructblip': [ 'INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InstructBlipConfig', 'InstructBlipQFormerConfig', 'InstructBlipVisionConfig', ], 'processing_instructblip': ['InstructBlipProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A =[ 'INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'InstructBlipQFormerModel', 'InstructBlipPreTrainedModel', 'InstructBlipForConditionalGeneration', 'InstructBlipVisionModel', ] if TYPE_CHECKING: from .configuration_instructblip import ( INSTRUCTBLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, InstructBlipConfig, InstructBlipQFormerConfig, InstructBlipVisionConfig, ) from .processing_instructblip import InstructBlipProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_instructblip import ( INSTRUCTBLIP_PRETRAINED_MODEL_ARCHIVE_LIST, InstructBlipForConditionalGeneration, InstructBlipPreTrainedModel, InstructBlipQFormerModel, InstructBlipVisionModel, ) else: import sys __A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
163
'''simple docstring''' import os import sys import unittest _lowerCamelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) _lowerCamelCase : str = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') _lowerCamelCase : Tuple = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : Any ): A = get_test_to_tester_mapping(_lowerCAmelCase ) A = get_test_to_tester_mapping(_lowerCAmelCase ) A = {"""BertModelTest""": """BertModelTester"""} A = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : str ): A = get_model_to_test_mapping(_lowerCAmelCase ) A = get_model_to_test_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): A = get_model_to_tester_mapping(_lowerCAmelCase ) A = get_model_to_tester_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase )
258
0
'''simple docstring''' def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ )-> float: '''simple docstring''' def get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) -> str: _UpperCAmelCase : Tuple = [] _UpperCAmelCase : str = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): _UpperCAmelCase : Optional[Any] = int(max(0 , i - limit ) ) _UpperCAmelCase : Optional[Any] = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCAmelCase_ ) _UpperCAmelCase : Union[str, Any] = F'''{_stra[0:_stra.index(lowerCAmelCase_ )]} {_stra[_stra.index(lowerCAmelCase_ ) + 1:]}''' return "".join(lowerCAmelCase_ ) # matching characters _UpperCAmelCase : Dict = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Tuple = get_matched_characters(lowerCAmelCase_ , lowerCAmelCase_ ) _UpperCAmelCase : Union[str, Any] = len(lowerCAmelCase_ ) # transposition _UpperCAmelCase : Union[str, Any] = ( len([(ca, ca) for ca, ca in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if ca != ca] ) // 2 ) if not match_count: _UpperCAmelCase : List[Any] = 0.0 else: _UpperCAmelCase : List[Any] = ( 1 / 3 * ( match_count / len(lowerCAmelCase_ ) + match_count / len(lowerCAmelCase_ ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters _UpperCAmelCase : Optional[Any] = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler("""hello""", """world"""))
215
'''simple docstring''' from __future__ import annotations def __a ( UpperCAmelCase , UpperCAmelCase ) ->Tuple: """simple docstring""" if len(UpperCAmelCase ) <= 1 or n <= 1: return insert_next(UpperCAmelCase , n - 1 ) rec_insertion_sort(UpperCAmelCase , n - 1 ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if index >= len(UpperCAmelCase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order A , A = ( collection[index], collection[index - 1], ) insert_next(UpperCAmelCase , index + 1 ) if __name__ == "__main__": _lowerCamelCase : List[Any] = input('Enter integers separated by spaces: ') _lowerCamelCase : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
258
0
def _lowerCamelCase( lowercase__ ) -> str: '''simple docstring''' return "".join([hex(lowercase__ )[2:].zfill(2 ).upper() for byte in list(lowercase__ )] ) def _lowerCamelCase( lowercase__ ) -> bytes: '''simple docstring''' if (len(lowercase__ ) % 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(lowercase__ ) <= 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(lowercase__ ) , 2 ) ) if __name__ == "__main__": import doctest doctest.testmod()
295
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def __a ( UpperCAmelCase ) ->Tuple: # picklable for multiprocessing """simple docstring""" return x.sum() def __a ( UpperCAmelCase ) ->int: # picklable for multiprocessing """simple docstring""" return i + 1 @dataclass class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = 42 __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def A (self : Tuple ): A = {} A = [] A = 1 A = [1, 2] A = {"""a""": 1, """b""": 2} A = {"""a""": [1, 2], """b""": [3, 4]} A = {"""a""": {"""1""": 1}, """b""": 2} A = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} A = {} A = [] A = 2 A = [2, 3] A = {"""a""": 2, """b""": 3} A = {"""a""": [2, 3], """b""": [4, 5]} A = {"""a""": {"""1""": 2}, """b""": 3} A = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) A = 2 self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) A = {"""a""": np.eye(2 ), """b""": np.zeros(3 ), """c""": np.ones(2 )} A = {"""a""": 2, """b""": 0, """c""": 2} A = { """a""": np.eye(2 ).astype(_lowerCAmelCase ), """b""": np.zeros(3 ).astype(_lowerCAmelCase ), """c""": np.ones(2 ).astype(_lowerCAmelCase ), } self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(_lowerCAmelCase ): # can't pickle a local lambda map_nested(lambda _lowerCAmelCase : x + 1 , _lowerCAmelCase , num_proc=_lowerCAmelCase ) def A (self : List[Any] ): A = {"""a""": 1, """b""": 2} A = {"""a""": 3, """b""": 4} A = {"""a""": 5, """b""": 6} A = sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = '''bar''' A = Foo() self.assertEqual(foo.my_attr , """bar""" ) with temporary_assignment(_lowerCAmelCase , """my_attr""" , """BAR""" ): self.assertEqual(foo.my_attr , """BAR""" ) self.assertEqual(foo.my_attr , """bar""" ) @pytest.mark.parametrize( """iterable_length, num_proc, expected_num_proc""" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Any: """simple docstring""" with patch("""datasets.utils.py_utils._single_map_nested""" ) as mock_single_map_nested, patch( """datasets.parallel.parallel.Pool""" ) as mock_multiprocessing_pool: A = {f"""{i}""": i for i in range(UpperCAmelCase )} A = map_nested(lambda UpperCAmelCase : x + 10 , UpperCAmelCase , num_proc=UpperCAmelCase , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class __UpperCAmelCase ( A__ ): '''simple docstring''' @require_tf def A (self : Dict ): import tensorflow as tf from tensorflow.keras import layers A = layers.Dense(2 ) def gen_random_output(): A = tf.random.uniform((1, 3) ) return model(_lowerCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def A (self : Tuple ): import torch def gen_random_output(): A = torch.nn.Linear(3 , 2 ) A = torch.rand(1 , 3 ) return model(_lowerCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def A (self : str ): def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): A = gen_random_output() with temp_seed(42 ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("""input_data""" , [{}] ) def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).data assert output_data == input_data @pytest.mark.parametrize( """data, expected_output""" , [ ({}, []), ([], []), ("""foo""", ["""foo"""]), (["""foo""", """bar"""], ["""foo""", """bar"""]), ([["""foo""", """bar"""]], ["""foo""", """bar"""]), ([[["""foo"""], ["""bar"""]]], ["""foo""", """bar"""]), ([[["""foo"""], """bar"""]], ["""foo""", """bar"""]), ({"""a""": 1, """b""": 2}, [1, 2]), ({"""a""": [1, 2], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[[3], [4]]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, [4]]}, [1, 2, 3, 4]), ({"""a""": {"""1""": 1}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": [2]}, [1, 2]), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->List[Any]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).flatten() assert output == expected_output def __a ( ) ->Optional[Any]: """simple docstring""" A = A(x=1 , y="""foobar""" ) A = {"""x""": 1, """y""": """foobar"""} assert asdict(UpperCAmelCase ) == expected_output A = {"""a""": {"""b""": A(x=10 , y="""foo""" )}, """c""": [A(x=20 , y="""bar""" )]} A = {"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]} assert asdict(UpperCAmelCase ) == expected_output with pytest.raises(UpperCAmelCase ): asdict([1, A(x=10 , y="""foo""" )] ) def __a ( UpperCAmelCase ) ->Tuple: """simple docstring""" return text.split() def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def __a ( ) ->Optional[int]: """simple docstring""" with Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: A = [] for yield_time, content in iflatmap_unordered( UpperCAmelCase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"""content""": """a"""}, {"""content""": """b"""}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(UpperCAmelCase ) assert out.count("""a""" ) == 2 assert out.count("""b""" ) == 2 assert len(UpperCAmelCase ) == 4
258
0
import os def a__ ( ): with open(os.path.dirname(__UpperCamelCase ) + "/grid.txt" ) as f: SCREAMING_SNAKE_CASE_ = [] # noqa: E741 for _ in range(2_0 ): l.append([int(__UpperCamelCase ) for x in f.readline().split()] ) SCREAMING_SNAKE_CASE_ = 0 # right for i in range(2_0 ): for j in range(1_7 ): SCREAMING_SNAKE_CASE_ = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: SCREAMING_SNAKE_CASE_ = temp # down for i in range(1_7 ): for j in range(2_0 ): SCREAMING_SNAKE_CASE_ = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: SCREAMING_SNAKE_CASE_ = temp # diagonal 1 for i in range(1_7 ): for j in range(1_7 ): SCREAMING_SNAKE_CASE_ = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: SCREAMING_SNAKE_CASE_ = temp # diagonal 2 for i in range(1_7 ): for j in range(3 , 2_0 ): SCREAMING_SNAKE_CASE_ = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: SCREAMING_SNAKE_CASE_ = temp return maximum if __name__ == "__main__": print(solution())
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __a ( ) ->None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
258
0
from __future__ import annotations from math import pi def snake_case ( snake_case__ :Union[str, Any] , snake_case__ :int , snake_case__ :Union[str, Any]) -> dict[str, float]: if (inductance, frequency, reactance).count(0) != 1: raise ValueError("""One and only one argument must be 0""") if inductance < 0: raise ValueError("""Inductance cannot be negative""") if frequency < 0: raise ValueError("""Frequency cannot be negative""") if reactance < 0: raise ValueError("""Inductive reactance cannot be negative""") if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError("""Exactly one argument must be 0""") if __name__ == "__main__": import doctest doctest.testmod()
180
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase : str = '\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n >>> repo = "openai/shap-e-img2img"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n >>> image = load_image(image_url).convert("RGB")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n ```\n' @dataclass class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : str , _lowerCAmelCase : PriorTransformer , _lowerCAmelCase : CLIPVisionModel , _lowerCAmelCase : CLIPImageProcessor , _lowerCAmelCase : HeunDiscreteScheduler , _lowerCAmelCase : ShapERenderer , ): super().__init__() self.register_modules( prior=_lowerCAmelCase , image_encoder=_lowerCAmelCase , image_processor=_lowerCAmelCase , scheduler=_lowerCAmelCase , renderer=_lowerCAmelCase , ) def A (self : Dict , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[Any] ): if latents is None: A = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) A = latents.to(_lowerCAmelCase ) A = latents * scheduler.init_noise_sigma return latents def A (self : Union[str, Any] , _lowerCAmelCase : List[Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A = torch.device(F"""cuda:{gpu_id}""" ) A = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCAmelCase , _lowerCAmelCase ) @property def A (self : Optional[Any] ): if self.device != torch.device("""meta""" ) or not hasattr(self.image_encoder , """_hf_hook""" ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_lowerCAmelCase , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def A (self : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Optional[int] , ): if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , torch.Tensor ): A = torch.cat(_lowerCAmelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase , axis=0 ) if not isinstance(_lowerCAmelCase , torch.Tensor ): A = self.image_processor(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values[0].unsqueeze(0 ) A = image.to(dtype=self.image_encoder.dtype , device=_lowerCAmelCase ) A = self.image_encoder(_lowerCAmelCase )["""last_hidden_state"""] A = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 A = image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: A = torch.zeros_like(_lowerCAmelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_lowerCAmelCase ) def __call__(self : List[Any] , _lowerCAmelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , _lowerCAmelCase : int = 1 , _lowerCAmelCase : int = 25 , _lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCAmelCase : Optional[torch.FloatTensor] = None , _lowerCAmelCase : float = 4.0 , _lowerCAmelCase : int = 64 , _lowerCAmelCase : Optional[str] = "pil" , _lowerCAmelCase : bool = True , ): if isinstance(_lowerCAmelCase , PIL.Image.Image ): A = 1 elif isinstance(_lowerCAmelCase , torch.Tensor ): A = image.shape[0] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): A = len(_lowerCAmelCase ) else: raise ValueError( F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCAmelCase )}""" ) A = self._execution_device A = batch_size * num_images_per_prompt A = guidance_scale > 1.0 A = self._encode_image(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # prior self.scheduler.set_timesteps(_lowerCAmelCase , device=_lowerCAmelCase ) A = self.scheduler.timesteps A = self.prior.config.num_embeddings A = self.prior.config.embedding_dim A = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim A = latents.reshape(latents.shape[0] , _lowerCAmelCase , _lowerCAmelCase ) for i, t in enumerate(self.progress_bar(_lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A = self.scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) A = self.prior( _lowerCAmelCase , timestep=_lowerCAmelCase , proj_embedding=_lowerCAmelCase , ).predicted_image_embedding # remove the variance A , A = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: A , A = noise_pred.chunk(2 ) A = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) A = self.scheduler.step( _lowerCAmelCase , timestep=_lowerCAmelCase , sample=_lowerCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_lowerCAmelCase ) A = [] for i, latent in enumerate(_lowerCAmelCase ): print() A = self.renderer.decode( latent[None, :] , _lowerCAmelCase , size=_lowerCAmelCase , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_lowerCAmelCase ) A = torch.stack(_lowerCAmelCase ) if output_type not in ["np", "pil"]: raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) A = images.cpu().numpy() if output_type == "pil": A = [self.numpy_to_pil(_lowerCAmelCase ) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_lowerCAmelCase )
258
0
'''simple docstring''' import unittest from transformers import DonutProcessor a__ : Any = 'naver-clova-ix/donut-base' class lowercase_ ( unittest.TestCase ): def __a ( self ): UpperCamelCase__ = DonutProcessor.from_pretrained(_lowerCAmelCase ) def __a ( self ): UpperCamelCase__ = { "name": "John Doe", "age": "99", "city": "Atlanta", "state": "GA", "zip": "30301", "phone": "123-4567", "nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}], } UpperCamelCase__ = ( "<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>" "<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>" "<s_nicknames><s_nickname>Johnny</s_nickname>" "<sep/><s_nickname>JD</s_nickname></s_nicknames>" ) UpperCamelCase__ = self.processor.tokenajson(_lowerCAmelCase ) self.assertDictEqual(_lowerCAmelCase , _lowerCAmelCase )
80
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class __UpperCAmelCase : '''simple docstring''' def __init__(self : Union[str, Any] , _lowerCAmelCase : Optional[int]=None , **_lowerCAmelCase : Union[str, Any] ): logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) A = model A = kwargs.get("""model_save_dir""" , _lowerCAmelCase ) A = kwargs.get("""latest_model_name""" , _lowerCAmelCase ) def __call__(self : Tuple , **_lowerCAmelCase : Optional[Any] ): A = {k: np.array(_lowerCAmelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCAmelCase , _lowerCAmelCase ) @staticmethod def A (_lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[Any]=None ): if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) A = """CPUExecutionProvider""" return ort.InferenceSession(_lowerCAmelCase , providers=[provider] , sess_options=_lowerCAmelCase ) def A (self : List[str] , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : List[str] ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME A = self.model_save_dir.joinpath(self.latest_model_name ) A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) A = self.model_save_dir.joinpath(_lowerCAmelCase ) if src_path.exists(): A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass def A (self : Tuple , _lowerCAmelCase : Union[str, os.PathLike] , **_lowerCAmelCase : str , ): if os.path.isfile(_lowerCAmelCase ): logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase ) # saving model weights/files self._save_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Union[bool, str, None]] = None , _lowerCAmelCase : Optional[Union[str, None]] = None , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional["ort.SessionOptions"] = None , **_lowerCAmelCase : Optional[int] , ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCAmelCase ): A = OnnxRuntimeModel.load_model( os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) A = Path(_lowerCAmelCase ) # load model from hub else: # download model A = hf_hub_download( repo_id=_lowerCAmelCase , filename=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , ) A = Path(_lowerCAmelCase ).parent A = Path(_lowerCAmelCase ).name A = OnnxRuntimeModel.load_model(_lowerCAmelCase , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) return cls(model=_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : str , ): A = None if len(str(_lowerCAmelCase ).split("""@""" ) ) == 2: A , A = model_id.split("""@""" ) return cls._from_pretrained( model_id=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , **_lowerCAmelCase , )
258
0
import unittest from pathlib import Path from shutil import copyfile from transformers import SPIECE_UNDERLINE, is_sentencepiece_available from transformers.models.speech_to_text import SpeechaTextTokenizer from transformers.models.speech_to_text.tokenization_speech_to_text import VOCAB_FILES_NAMES, save_json from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_sentencepiece_available(): import sentencepiece as sp SCREAMING_SNAKE_CASE__ = 5 SCREAMING_SNAKE_CASE__ = 10 @require_sentencepiece @require_tokenizers class A__ ( A__ , unittest.TestCase ): lowerCAmelCase__ : str = SpeechaTextTokenizer lowerCAmelCase__ : Optional[Any] = False lowerCAmelCase__ : Dict = True def a__ ( self : Any ) -> List[Any]: """simple docstring""" super().setUp() __lowercase = sp.SentencePieceProcessor() spm_model.Load(_lowerCAmelCase ) __lowercase = ['<s>', '<pad>', '</s>', '<unk>'] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(_lowerCAmelCase ) )] __lowercase = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) __lowercase = Path(self.tmpdirname ) save_json(_lowerCAmelCase , save_dir / VOCAB_FILES_NAMES['vocab_file'] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(_lowerCAmelCase , save_dir / VOCAB_FILES_NAMES['spm_file'] ) __lowercase = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def a__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowercase = '<pad>' __lowercase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) , _lowerCAmelCase ) def a__ ( self : List[str] ) -> Tuple: """simple docstring""" __lowercase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(_lowerCAmelCase ) , 10_01 ) def a__ ( self : List[Any] ) -> Any: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_01 ) def a__ ( self : Tuple ) -> Tuple: """simple docstring""" __lowercase = SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) __lowercase = tokenizer.tokenize('This is a test' ) self.assertListEqual(_lowerCAmelCase , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [2_89, 50, 14, 1_74, 3_86] , ) __lowercase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( _lowerCAmelCase , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) __lowercase = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , [12, 25, 88, 59, 28, 23, 11, 4, 6_06, 3_51, 3_51, 3_51, 7, 16, 70, 50, 76, 84, 10, 4, 8] ) __lowercase = tokenizer.convert_ids_to_tokens(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def a__ ( self : Optional[Any] ) -> str: """simple docstring""" __lowercase = {'input_ids': [[37_91, 7_97, 31, 11, 64, 7_97, 31, 24_29, 4_33, 12, 11_76, 12, 20, 7_86, 9_15, 1_42, 24_13, 2_40, 37, 32_38, 7_97, 31, 11, 35, 93, 9_15, 1_42, 24_13, 2_40, 37, 55_40, 5_67, 12_76, 93, 37, 6_10, 40, 62, 4_55, 6_57, 10_42, 1_23, 7_80, 1_77, 37, 3_09, 2_41, 12_98, 5_14, 20, 2_92, 27_37, 1_14, 24_69, 2_41, 85, 64, 3_02, 5_48, 5_28, 4_23, 4, 5_09, 4_06, 4_23, 37, 6_01, 4, 7_77, 3_02, 5_48, 5_28, 4_23, 2_84, 4, 33_88, 5_11, 4_59, 4, 35_55, 40, 3_21, 3_02, 7_05, 4, 33_88, 5_11, 5_83, 3_26, 5, 5, 5, 62, 33_10, 5_60, 1_77, 26_80, 2_17, 15_08, 32, 31, 8_53, 4_18, 64, 5_83, 5_11, 16_05, 62, 35, 93, 5_60, 1_77, 26_80, 2_17, 15_08, 15_21, 64, 5_83, 5_11, 5_19, 62, 20, 15_15, 7_64, 20, 1_49, 2_61, 56_25, 79_72, 20, 55_40, 5_67, 12_76, 93, 39_25, 16_75, 11, 15, 8_02, 79_72, 5_76, 2_17, 15_08, 11, 35, 93, 12_53, 24_41, 15, 2_89, 6_52, 31, 4_16, 3_21, 38_42, 1_15, 40, 9_11, 8, 4_76, 6_19, 4, 3_80, 1_42, 4_23, 3_35, 2_40, 35, 93, 2_64, 8, 11, 3_35, 5_69, 4_20, 1_63, 5, 2], [2_60, 5_48, 5_28, 4_23, 20, 4_51, 20, 26_81, 11_53, 34_34, 20, 55_40, 37, 5_67, 1_26, 12_53, 24_41, 33_76, 4_49, 2_10, 4_31, 15_63, 1_77, 7_67, 55_40, 11, 12_03, 4_72, 11, 29_53, 6_85, 2_85, 3_64, 7_06, 11_53, 20, 67_99, 20, 28_69, 20, 44_64, 1_26, 40, 24_29, 20, 10_40, 8_66, 26_64, 4_18, 20, 3_18, 20, 17_26, 1_86, 20, 2_65, 5_22, 35, 93, 21_91, 46_34, 20, 10_40, 12, 67_99, 15, 2_28, 23_56, 1_42, 31, 11, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_75, 26_66, 6_84, 15_82, 11_76, 12, 6_27, 1_49, 6_19, 20, 49_02, 5_63, 11, 20, 1_49, 2_61, 34_20, 23_56, 1_74, 1_42, 47_14, 1_31, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCAmelCase , model_name='facebook/s2t-small-mustc-en-de-st' , revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' , ) @require_sentencepiece class A__ ( unittest.TestCase ): lowerCAmelCase__ : Optional[int] = "valhalla/s2t_mustc_multilinguial_medium" lowerCAmelCase__ : List[Any] = "C\'est trop cool" lowerCAmelCase__ : Optional[int] = "Esto es genial" @classmethod def a__ ( cls : Tuple ) -> List[str]: """simple docstring""" __lowercase = SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def a__ ( self : List[str] ) -> Tuple: """simple docstring""" self.assertEqual(self.tokenizer.lang_code_to_id['pt'] , 4 ) self.assertEqual(self.tokenizer.lang_code_to_id['ru'] , 6 ) self.assertEqual(self.tokenizer.lang_code_to_id['it'] , 9 ) self.assertEqual(self.tokenizer.lang_code_to_id['de'] , 11 ) def a__ ( self : List[str] ) -> Any: """simple docstring""" self.assertEqual(self.tokenizer.vocab_size , 1_00_00 ) def a__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" self.assertIn(_lowerCAmelCase , self.tokenizer.all_special_ids ) __lowercase = [ES_CODE, 4, 16_01, 47, 76_47, 2] __lowercase = self.tokenizer.decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase ) __lowercase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_lowerCAmelCase ) self.assertEqual(_lowerCAmelCase , _lowerCAmelCase ) self.assertNotIn(self.tokenizer.eos_token , _lowerCAmelCase ) def a__ ( self : str ) -> List[str]: """simple docstring""" __lowercase = 'fr' __lowercase = self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , _lowerCAmelCase ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def a__ ( self : List[str] ) -> int: """simple docstring""" __lowercase = 'fr' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) __lowercase = 'es' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
325
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def A (self : str , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : str ): A = hf_hub_download( repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) A = VideoClassificationPipeline(model=_lowerCAmelCase , image_processor=_lowerCAmelCase , top_k=2 ) A = [ example_video_filepath, """https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4""", ] return video_classifier, examples def A (self : Optional[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[Any] ): for example in examples: A = video_classifier(_lowerCAmelCase ) self.assertEqual( _lowerCAmelCase , [ {"""score""": ANY(_lowerCAmelCase ), """label""": ANY(_lowerCAmelCase )}, {"""score""": ANY(_lowerCAmelCase ), """label""": ANY(_lowerCAmelCase )}, ] , ) @require_torch def A (self : Optional[Any] ): A = """hf-internal-testing/tiny-random-VideoMAEForVideoClassification""" A = VideoMAEFeatureExtractor( size={"""shortest_edge""": 10} , crop_size={"""height""": 10, """width""": 10} ) A = pipeline( """video-classification""" , model=_lowerCAmelCase , feature_extractor=_lowerCAmelCase , frame_sampling_rate=4 ) A = hf_hub_download(repo_id="""nateraw/video-demo""" , filename="""archery.mp4""" , repo_type="""dataset""" ) A = video_classifier(_lowerCAmelCase , top_k=2 ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}] , ) A = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowerCAmelCase , decimals=4 ) , [ [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}], [{"""score""": 0.5_199, """label""": """LABEL_0"""}, {"""score""": 0.4_801, """label""": """LABEL_1"""}], ] , ) @require_tf def A (self : List[Any] ): pass
258
0
def _UpperCAmelCase ( snake_case ): """simple docstring""" _lowerCAmelCase = len(snake_case ) for i in range(1 , snake_case ): _lowerCAmelCase = collection[i] _lowerCAmelCase = 0 _lowerCAmelCase = i - 1 while low <= high: _lowerCAmelCase = (low + high) // 2 if val < collection[mid]: _lowerCAmelCase = mid - 1 else: _lowerCAmelCase = mid + 1 for j in range(snake_case , snake_case , -1 ): _lowerCAmelCase = collection[j - 1] _lowerCAmelCase = val return collection if __name__ == "__main__": A__ = input("""Enter numbers separated by a comma:\n""").strip() A__ = [int(item) for item in user_input.split(""",""")] print(binary_insertion_sort(unsorted))
82
'''simple docstring''' from __future__ import annotations # This is the precision for this function which can be altered. # It is recommended for users to keep this number greater than or equal to 10. _lowerCamelCase : int = 10 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" for i in range(UpperCAmelCase , UpperCAmelCase ): if array[i] == target: return i return -1 def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" A = 0 A = len(UpperCAmelCase ) while left <= right: if right - left < precision: return lin_search(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) A = (left + right) // 3 + 1 A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: A = one_third - 1 elif array[two_third] < target: A = two_third + 1 else: A = one_third + 1 A = two_third - 1 else: return -1 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if left < right: if right - left < precision: return lin_search(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) A = (left + right) // 3 + 1 A = 2 * (left + right) // 3 + 1 if array[one_third] == target: return one_third elif array[two_third] == target: return two_third elif target < array[one_third]: return rec_ternary_search(UpperCAmelCase , one_third - 1 , UpperCAmelCase , UpperCAmelCase ) elif array[two_third] < target: return rec_ternary_search(two_third + 1 , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) else: return rec_ternary_search(one_third + 1 , two_third - 1 , UpperCAmelCase , UpperCAmelCase ) else: return -1 if __name__ == "__main__": import doctest doctest.testmod() _lowerCamelCase : str = input('Enter numbers separated by comma:\n').strip() _lowerCamelCase : str = [int(item.strip()) for item in user_input.split(',')] assert collection == sorted(collection), f"List must be ordered.\n{collection}." _lowerCamelCase : Optional[int] = int(input('Enter the number to be found in the list:\n').strip()) _lowerCamelCase : Union[str, Any] = ite_ternary_search(collection, target) _lowerCamelCase : Union[str, Any] = rec_ternary_search(0, len(collection) - 1, collection, target) if resulta != -1: print(f"Iterative search: {target} found at positions: {resulta}") print(f"Recursive search: {target} found at positions: {resulta}") else: print('Not found')
258
0
import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __SCREAMING_SNAKE_CASE( A__ , unittest.TestCase ): _UpperCAmelCase = BioGptTokenizer _UpperCAmelCase = False def lowerCAmelCase_ ( self: int ) -> List[str]: super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'w</w>', 'r</w>', 't</w>', 'lo', 'low', 'er</w>', 'low</w>', 'lowest</w>', 'newer</w>', 'wider</w>', '<unk>', ] snake_case__ = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) snake_case__ = ['l o 123', 'lo w 1456', 'e r</w> 1789', ''] snake_case__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) snake_case__ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' ) as fp: fp.write(json.dumps(_lowerCAmelCase ) ) with open(self.merges_file , 'w' ) as fp: fp.write('\n'.join(_lowerCAmelCase ) ) def lowerCAmelCase_ ( self: Tuple , UpperCamelCase: List[str] ) -> List[Any]: snake_case__ = 'lower newer' snake_case__ = 'lower newer' return input_text, output_text def lowerCAmelCase_ ( self: List[Any] ) -> Tuple: snake_case__ = BioGptTokenizer(self.vocab_file , self.merges_file ) snake_case__ = 'lower' snake_case__ = ['low', 'er</w>'] snake_case__ = tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) snake_case__ = tokens + ['<unk>'] snake_case__ = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , _lowerCAmelCase ) @slow def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[Any]: snake_case__ = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) snake_case__ = tokenizer.encode('sequence builders' , add_special_tokens=_lowerCAmelCase ) snake_case__ = tokenizer.encode('multi-sequence build' , add_special_tokens=_lowerCAmelCase ) snake_case__ = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) snake_case__ = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
307
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = CycleDiffusionPipeline __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - { '''negative_prompt''', '''height''', '''width''', '''negative_prompt_embeds''', } __lowerCAmelCase = PipelineTesterMixin.required_optional_params - {'''latents'''} __lowerCAmelCase = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'''source_prompt'''} ) __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS __lowerCAmelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def A (self : int ): torch.manual_seed(0 ) A = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) A = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , num_train_timesteps=1000 , clip_sample=_lowerCAmelCase , set_alpha_to_one=_lowerCAmelCase , ) torch.manual_seed(0 ) A = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) A = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) A = CLIPTextModel(_lowerCAmelCase ) A = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) A = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def A (self : Dict , _lowerCAmelCase : str , _lowerCAmelCase : List[str]=0 ): A = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCAmelCase ) ).to(_lowerCAmelCase ) A = image / 2 + 0.5 if str(_lowerCAmelCase ).startswith("""mps""" ): A = torch.manual_seed(_lowerCAmelCase ) else: A = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase ) A = { """prompt""": """An astronaut riding an elephant""", """source_prompt""": """An astronaut riding a horse""", """image""": image, """generator""": generator, """num_inference_steps""": 2, """eta""": 0.1, """strength""": 0.8, """guidance_scale""": 3, """source_guidance_scale""": 1, """output_type""": """numpy""", } return inputs def A (self : Any ): A = """cpu""" # ensure determinism for the device-dependent torch.Generator A = self.get_dummy_components() A = CycleDiffusionPipeline(**_lowerCAmelCase ) A = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) A = self.get_dummy_inputs(_lowerCAmelCase ) A = pipe(**_lowerCAmelCase ) A = output.images A = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) A = np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @unittest.skipIf(torch_device != """cuda""" , """This test requires a GPU""" ) def A (self : str ): A = self.get_dummy_components() for name, module in components.items(): if hasattr(_lowerCAmelCase , """half""" ): A = module.half() A = CycleDiffusionPipeline(**_lowerCAmelCase ) A = pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) A = self.get_dummy_inputs(_lowerCAmelCase ) A = pipe(**_lowerCAmelCase ) A = output.images A = images[0, -3:, -3:, -1] assert images.shape == (1, 32, 32, 3) A = np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @skip_mps def A (self : Optional[int] ): return super().test_save_load_local() @unittest.skip("""non-deterministic pipeline""" ) def A (self : Optional[Any] ): return super().test_inference_batch_single_identical() @skip_mps def A (self : Dict ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def A (self : Optional[Any] ): return super().test_save_load_optional_components() @skip_mps def A (self : Optional[int] ): return super().test_attention_slicing_forward_pass() @slow @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A (self : int ): A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy""" ) A = init_image.resize((512, 512) ) A = """CompVis/stable-diffusion-v1-4""" A = DDIMScheduler.from_pretrained(_lowerCAmelCase , subfolder="""scheduler""" ) A = CycleDiffusionPipeline.from_pretrained( _lowerCAmelCase , scheduler=_lowerCAmelCase , safety_checker=_lowerCAmelCase , torch_dtype=torch.floataa , revision="""fp16""" ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() A = """A black colored car""" A = """A blue colored car""" A = torch.manual_seed(0 ) A = pipe( prompt=_lowerCAmelCase , source_prompt=_lowerCAmelCase , image=_lowerCAmelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCAmelCase , output_type="""np""" , ) A = output.images # the values aren't exactly equal, but the images look the same visually assert np.abs(image - expected_image ).max() < 5e-1 def A (self : int ): A = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/cycle-diffusion/black_colored_car.png""" ) A = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy""" ) A = init_image.resize((512, 512) ) A = """CompVis/stable-diffusion-v1-4""" A = DDIMScheduler.from_pretrained(_lowerCAmelCase , subfolder="""scheduler""" ) A = CycleDiffusionPipeline.from_pretrained(_lowerCAmelCase , scheduler=_lowerCAmelCase , safety_checker=_lowerCAmelCase ) pipe.to(_lowerCAmelCase ) pipe.set_progress_bar_config(disable=_lowerCAmelCase ) pipe.enable_attention_slicing() A = """A black colored car""" A = """A blue colored car""" A = torch.manual_seed(0 ) A = pipe( prompt=_lowerCAmelCase , source_prompt=_lowerCAmelCase , image=_lowerCAmelCase , num_inference_steps=100 , eta=0.1 , strength=0.85 , guidance_scale=3 , source_guidance_scale=1 , generator=_lowerCAmelCase , output_type="""np""" , ) A = output.images assert np.abs(image - expected_image ).max() < 2e-2
258
0
import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : str = np.full((len(SCREAMING_SNAKE_CASE__ ), sequence_length, 2) , SCREAMING_SNAKE_CASE__ ) else: lowercase : Dict = np.full((len(SCREAMING_SNAKE_CASE__ ), sequence_length) , SCREAMING_SNAKE_CASE__ ) for i, tensor in enumerate(SCREAMING_SNAKE_CASE__ ): if padding_side == "right": if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : Optional[Any] = tensor[:sequence_length] else: lowercase : List[Any] = tensor[:sequence_length] else: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): lowercase : List[Any] = tensor[:sequence_length] else: lowercase : Optional[int] = tensor[:sequence_length] return out_tensor.tolist() def _snake_case( SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: lowercase : Dict = ord(SCREAMING_SNAKE_CASE__ ) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True lowercase : List[Any] = unicodedata.category(SCREAMING_SNAKE_CASE__ ) if cat.startswith("""P""" ): return True return False @dataclass class __snake_case ( A__ ): _a : Dict= 42 _a : Optional[Any]= True _a : Any= None _a : str= None _a : Optional[int]= -100 _a : Union[str, Any]= "pt" def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' import torch lowercase : str = """label""" if """label""" in features[0].keys() else """labels""" lowercase : str = [feature[label_name] for feature in features] if label_name in features[0].keys() else None lowercase : Union[str, Any] = self.tokenizer.pad( _lowerCAmelCase ,padding=self.padding ,max_length=self.max_length ,pad_to_multiple_of=self.pad_to_multiple_of ,return_tensors="""pt""" if labels is None else None ,) if labels is None: return batch lowercase : List[str] = torch.tensor(batch["""entity_ids"""] ).shape[1] lowercase : str = self.tokenizer.padding_side if padding_side == "right": lowercase : str = [ list(_lowerCAmelCase ) + [self.label_pad_token_id] * (sequence_length - len(_lowerCAmelCase )) for label in labels ] else: lowercase : Tuple = [ [self.label_pad_token_id] * (sequence_length - len(_lowerCAmelCase )) + list(_lowerCAmelCase ) for label in labels ] lowercase : List[Any] = [feature["""ner_tags"""] for feature in features] lowercase : List[Any] = padding_tensor(_lowerCAmelCase ,-1 ,_lowerCAmelCase ,_lowerCAmelCase ) lowercase : Optional[Any] = [feature["""original_entity_spans"""] for feature in features] lowercase : List[Any] = padding_tensor(_lowerCAmelCase ,(-1, -1) ,_lowerCAmelCase ,_lowerCAmelCase ) lowercase : Tuple = {k: torch.tensor(_lowerCAmelCase ,dtype=torch.intaa ) for k, v in batch.items()} return batch
20
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) @add_end_docstrings(A__ ) class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : Tuple , *_lowerCAmelCase : List[str] , **_lowerCAmelCase : List[str] ): super().__init__(*_lowerCAmelCase , **_lowerCAmelCase ) requires_backends(self , """vision""" ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == """tf""" else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def A (self : Any , _lowerCAmelCase : str=None ): A = {} if top_k is not None: A = top_k return {}, {}, postprocess_params def __call__(self : str , _lowerCAmelCase : Union[str, List[str], "Image.Image", List["Image.Image"]] , **_lowerCAmelCase : int ): return super().__call__(_lowerCAmelCase , **_lowerCAmelCase ) def A (self : List[str] , _lowerCAmelCase : List[Any] ): A = load_image(_lowerCAmelCase ) A = self.image_processor(images=_lowerCAmelCase , return_tensors=self.framework ) return model_inputs def A (self : Union[str, Any] , _lowerCAmelCase : Optional[int] ): A = self.model(**_lowerCAmelCase ) return model_outputs def A (self : Optional[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=5 ): if top_k > self.model.config.num_labels: A = self.model.config.num_labels if self.framework == "pt": A = model_outputs.logits.softmax(-1 )[0] A , A = probs.topk(_lowerCAmelCase ) elif self.framework == "tf": A = stable_softmax(model_outputs.logits , axis=-1 )[0] A = tf.math.top_k(_lowerCAmelCase , k=_lowerCAmelCase ) A , A = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F"""Unsupported framework: {self.framework}""" ) A = scores.tolist() A = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_lowerCAmelCase , _lowerCAmelCase )]
258
0
from math import factorial class UpperCAmelCase : '''simple docstring''' def __init__( self : Optional[Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : int ): """simple docstring""" _A: int = real if isinstance(_lowerCAmelCase , _lowerCAmelCase ): _A: Tuple = [1] * rank else: _A: str = rank def __repr__( self : str ): """simple docstring""" return ( F"""{self.real}+""" F"""{'+'.join(str(_lowerCAmelCase )+'E'+str(n+1 )for n,dual in enumerate(self.duals ) )}""" ) def __magic_name__ ( self : List[Any] ): """simple docstring""" _A: Union[str, Any] = self.duals.copy() while cur[-1] == 0: cur.pop(-1 ) return Dual(self.real , _lowerCAmelCase ) def __add__( self : int , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): return Dual(self.real + other , self.duals ) _A: Any = self.duals.copy() _A: Union[str, Any] = other.duals.copy() if len(_lowerCAmelCase ) > len(_lowerCAmelCase ): o_dual.extend([1] * (len(_lowerCAmelCase ) - len(_lowerCAmelCase )) ) elif len(_lowerCAmelCase ) < len(_lowerCAmelCase ): s_dual.extend([1] * (len(_lowerCAmelCase ) - len(_lowerCAmelCase )) ) _A: Optional[Any] = [] for i in range(len(_lowerCAmelCase ) ): new_duals.append(s_dual[i] + o_dual[i] ) return Dual(self.real + other.real , _lowerCAmelCase ) __UpperCamelCase : List[str] = __add__ def __sub__( self : Any , lowerCAmelCase_ : List[str] ): """simple docstring""" return self + other * -1 def __mul__( self : Union[str, Any] , lowerCAmelCase_ : Optional[Any] ): """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): _A: Any = [] for i in self.duals: new_duals.append(i * other ) return Dual(self.real * other , _lowerCAmelCase ) _A: List[Any] = [0] * (len(self.duals ) + len(other.duals ) + 1) for i, item in enumerate(self.duals ): for j, jtem in enumerate(other.duals ): new_duals[i + j + 1] += item * jtem for k in range(len(self.duals ) ): new_duals[k] += self.duals[k] * other.real for index in range(len(other.duals ) ): new_duals[index] += other.duals[index] * self.real return Dual(self.real * other.real , _lowerCAmelCase ) __UpperCamelCase : Optional[int] = __mul__ def __truediv__( self : List[str] , lowerCAmelCase_ : str ): """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): _A: Optional[Any] = [] for i in self.duals: new_duals.append(i / other ) return Dual(self.real / other , _lowerCAmelCase ) raise ValueError def __floordiv__( self : Any , lowerCAmelCase_ : List[str] ): """simple docstring""" if not isinstance(_lowerCAmelCase , _lowerCAmelCase ): _A: Optional[int] = [] for i in self.duals: new_duals.append(i // other ) return Dual(self.real // other , _lowerCAmelCase ) raise ValueError def __pow__( self : Any , lowerCAmelCase_ : List[str] ): """simple docstring""" if n < 0 or isinstance(_lowerCAmelCase , _lowerCAmelCase ): raise ValueError('''power must be a positive integer''' ) if n == 0: return 1 if n == 1: return self _A: Dict = self for _ in range(n - 1 ): x *= self return x def lowerCamelCase__ ( a , a , a ) -> Any: if not callable(a ): raise ValueError('''differentiate() requires a function as input for func''' ) if not isinstance(a , (float, int) ): raise ValueError('''differentiate() requires a float as input for position''' ) if not isinstance(a , a ): raise ValueError('''differentiate() requires an int as input for order''' ) _A: Tuple = Dual(a , 1 ) _A: List[Any] = func(a ) if order == 0: return result.real return result.duals[order - 1] * factorial(a ) if __name__ == "__main__": import doctest doctest.testmod() def lowerCamelCase__ ( a ) -> Union[str, Any]: return y**2 * y**4 print(differentiate(f, 9, 2))
121
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" if density <= 0: raise ValueError("""Impossible fluid density""" ) if bulk_modulus <= 0: raise ValueError("""Impossible bulk modulus""" ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
258
0
'''simple docstring''' import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": __A =argparse.ArgumentParser( description=( 'Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned' ' Distillation' ) ) parser.add_argument('--model_type', default='bert', choices=['bert']) parser.add_argument('--model_name', default='bert-base-uncased', type=str) parser.add_argument('--dump_checkpoint', default='serialization_dir/tf_bert-base-uncased_0247911.pth', type=str) parser.add_argument('--vocab_transform', action='store_true') __A =parser.parse_args() if args.model_type == "bert": __A =BertForMaskedLM.from_pretrained(args.model_name) __A ='bert' else: raise ValueError('args.model_type should be "bert".') __A =model.state_dict() __A ={} for w in ["word_embeddings", "position_embeddings"]: __A =state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: __A =state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] __A =0 for teacher_idx in [0, 2, 4, 7, 9, 11]: for w in ["weight", "bias"]: __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] __A =state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 __A =state_dict['cls.predictions.decoder.weight'] __A =state_dict['cls.predictions.bias'] if args.vocab_transform: for w in ["weight", "bias"]: __A =state_dict[f"""cls.predictions.transform.dense.{w}"""] __A =state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
163
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class __UpperCAmelCase ( A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = BioGptTokenizer __lowerCAmelCase = False def A (self : int ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt A = [ """l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """w</w>""", """r</w>""", """t</w>""", """lo""", """low""", """er</w>""", """low</w>""", """lowest</w>""", """newer</w>""", """wider</w>""", """<unk>""", ] A = dict(zip(_lowerCAmelCase , range(len(_lowerCAmelCase ) ) ) ) A = ["""l o 123""", """lo w 1456""", """e r</w> 1789""", """"""] A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) A = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" ) as fp: fp.write(json.dumps(_lowerCAmelCase ) ) with open(self.merges_file , """w""" ) as fp: fp.write("""\n""".join(_lowerCAmelCase ) ) def A (self : Tuple , _lowerCAmelCase : List[str] ): A = """lower newer""" A = """lower newer""" return input_text, output_text def A (self : List[Any] ): A = BioGptTokenizer(self.vocab_file , self.merges_file ) A = """lower""" A = ["""low""", """er</w>"""] A = tokenizer.tokenize(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) A = tokens + ["""<unk>"""] A = [14, 15, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , _lowerCAmelCase ) @slow def A (self : Union[str, Any] ): A = BioGptTokenizer.from_pretrained("""microsoft/biogpt""" ) A = tokenizer.encode("""sequence builders""" , add_special_tokens=_lowerCAmelCase ) A = tokenizer.encode("""multi-sequence build""" , add_special_tokens=_lowerCAmelCase ) A = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase ) A = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
258
0
'''simple docstring''' import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin A_ : Optional[int] = get_tests_dir("""fixtures/test_sentencepiece_with_bytefallback.model""") @require_sentencepiece @require_tokenizers class lowercase ( A__ , unittest.TestCase ): """simple docstring""" UpperCAmelCase = GPTSwaTokenizer UpperCAmelCase = False UpperCAmelCase = True UpperCAmelCase = False def _snake_case ( self ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing _UpperCAmelCase : Dict = GPTSwaTokenizer(_lowerCAmelCase ,eos_token="""<unk>""" ,bos_token="""<unk>""" ,pad_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self ,a_ ) -> Optional[int]: _UpperCAmelCase : Union[str, Any] = """This is a test""" _UpperCAmelCase : List[Any] = """This is a test""" return input_text, output_text def _snake_case ( self ) -> int: _UpperCAmelCase : str = """<s>""" _UpperCAmelCase : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) ,_lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) ,_lowerCAmelCase ) def _snake_case ( self ) -> Optional[int]: _UpperCAmelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"""<unk>""" ) self.assertEqual(vocab_keys[1] ,"""<s>""" ) self.assertEqual(vocab_keys[-1] ,"""j""" ) self.assertEqual(len(_lowerCAmelCase ) ,2_000 ) def _snake_case ( self ) -> Optional[Any]: self.assertEqual(self.get_tokenizer().vocab_size ,2_000 ) def _snake_case ( self ) -> Any: _UpperCAmelCase : Union[str, Any] = GPTSwaTokenizer(_lowerCAmelCase ) _UpperCAmelCase : Tuple = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(_lowerCAmelCase ,["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) ,[465, 287, 265, 631, 842] ) _UpperCAmelCase : Optional[Any] = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) # fmt: off self.assertListEqual( _lowerCAmelCase ,["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ,) # fmt: on _UpperCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) self.assertListEqual( _lowerCAmelCase ,[262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] ,) _UpperCAmelCase : int = tokenizer.convert_ids_to_tokens(_lowerCAmelCase ) # fmt: off self.assertListEqual( _lowerCAmelCase ,["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ) # fmt: on def _snake_case ( self ) -> Any: _UpperCAmelCase : int = GPTSwaTokenizer(_lowerCAmelCase ) _UpperCAmelCase : int = ["""This is a test""", """I was born in 92000, and this is falsé."""] _UpperCAmelCase : Any = [ [465, 287, 265, 631, 842], [262, 272, 1_525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(_lowerCAmelCase ,_lowerCAmelCase ): self.assertListEqual(tokenizer.encode_fast(_lowerCAmelCase ) ,_lowerCAmelCase ) # Test that decode_fast returns the input text for text, token_ids in zip(_lowerCAmelCase ,_lowerCAmelCase ): self.assertEqual(tokenizer.decode_fast(_lowerCAmelCase ) ,_lowerCAmelCase ) @slow def _snake_case ( self ) -> Union[str, Any]: _UpperCAmelCase : Tuple = [ """<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off _UpperCAmelCase : Union[str, Any] = {"""input_ids""": [[63_423, 5, 6_811, 14_954, 282, 816, 3_821, 63_466, 63_425, 63_462, 18, 63_978, 678, 301, 1_320, 63_423, 63_455, 63_458, 18, 63_982, 4_246, 3_940, 1_901, 47_789, 5_547, 18_994], [19_630, 1_100, 63_446, 1_342, 633, 544, 4_488, 593, 5_102, 2_416, 63_495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_652, 428, 268, 1_936, 515, 268, 58_593, 22_413, 9_106, 546, 268, 33_213, 63_979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55_130, 63_450, 924, 63_449, 2_249, 4_062, 1_558, 318, 63_504, 21_498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2_827, 2_559, 332, 6_575, 63_443, 26_801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCAmelCase ,model_name="""AI-Sweden/gpt-sw3-126m""" ,sequences=_lowerCAmelCase ,)
215
'''simple docstring''' from __future__ import annotations import numpy as np def __a ( UpperCAmelCase ) ->Optional[int]: """simple docstring""" return np.maximum(0 , UpperCAmelCase ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
258
0
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 = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class A ( A__ , unittest.TestCase ): UpperCamelCase_ : Any =PegasusTokenizer UpperCamelCase_ : Optional[int] =PegasusTokenizerFast UpperCamelCase_ : int =True UpperCamelCase_ : int =True def _A (self ): super().setUp() # We have a SentencePiece fixture for testing __lowercase= PegasusTokenizer(_lowerCAmelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _A (self ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _A (self , **lowerCAmelCase ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def _A (self , lowerCAmelCase ): return ("This is a test", "This is a test") def _A (self ): __lowercase= '</s>' __lowercase= 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCAmelCase ) , _lowerCAmelCase ) def _A (self ): __lowercase= 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(_lowerCAmelCase ) , 1_1_0_3 ) def _A (self ): self.assertEqual(self.get_tokenizer().vocab_size , 1_1_0_3 ) def _A (self ): __lowercase= self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase= self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase= ( '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>' ) __lowercase= rust_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] __lowercase= py_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def _A (self ): __lowercase= self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowercase= '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowercase= [2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __lowercase= tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def _A (self ): __lowercase= self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6_1_0_3 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_0_3 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_0_2_4 __lowercase= 'To ensure a smooth flow of bank resolutions.' __lowercase= [4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __lowercase= tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _A (self ): __lowercase= ['This is going to be way too long.' * 1_5_0, 'short example'] __lowercase= ['not super long but more than 5 tokens', 'tiny'] __lowercase= self._large_tokenizer(_lowerCAmelCase , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors='pt' ) __lowercase= self._large_tokenizer( text_target=_lowerCAmelCase , max_length=5 , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1_0_2_4) assert batch.attention_mask.shape == (2, 1_0_2_4) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCAmelCase ) == 2 # input_ids, attention_mask. @slow def _A (self ): # fmt: off __lowercase= {'input_ids': [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0_6, 1_3_0, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 5_4_1_8_9, 1_1_2_9, 1_1_1, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 9_1_1_4, 1_4_7_8_7, 1_2_1, 1_3_2_4_9, 1_5_8, 5_9_2, 9_5_6, 1_2_1, 1_4_6_2_1, 3_1_5_7_6, 1_4_3, 6_2_6_1_3, 1_0_8, 9_6_8_8, 9_3_0, 4_3_4_3_0, 1_1_5_6_2, 6_2_6_1_3, 3_0_4, 1_0_8, 1_1_4_4_3, 8_9_7, 1_0_8, 9_3_1_4, 1_7_4_1_5, 6_3_3_9_9, 1_0_8, 1_1_4_4_3, 7_6_1_4, 1_8_3_1_6, 1_1_8, 4_2_8_4, 7_1_4_8, 1_2_4_3_0, 1_4_3, 1_4_0_0, 2_5_7_0_3, 1_5_8, 1_1_1, 4_2_8_4, 7_1_4_8, 1_1_7_7_2, 1_4_3, 2_1_2_9_7, 1_0_6_4, 1_5_8, 1_2_2, 2_0_4, 3_5_0_6, 1_7_5_4, 1_1_3_3, 1_4_7_8_7, 1_5_8_1, 1_1_5, 3_3_2_2_4, 4_4_8_2, 1_1_1, 1_3_5_5, 1_1_0, 2_9_1_7_3, 3_1_7, 5_0_8_3_3, 1_0_8, 2_0_1_4_7, 9_4_6_6_5, 1_1_1, 7_7_1_9_8, 1_0_7, 1], [1_1_0, 6_2_6_1_3, 1_1_7, 6_3_8, 1_1_2, 1_1_3_3, 1_2_1, 2_0_0_9_8, 1_3_5_5, 7_9_0_5_0, 1_3_8_7_2, 1_3_5, 1_5_9_6, 5_3_5_4_1, 1_3_5_2, 1_4_1, 1_3_0_3_9, 5_5_4_2, 1_2_4, 3_0_2, 5_1_8, 1_1_1, 2_6_8, 2_9_5_6, 1_1_5, 1_4_9, 4_4_2_7, 1_0_7, 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_3_9, 1_2_3_5, 2_7_9_9, 1_8_2_8_9, 1_7_7_8_0, 2_0_4, 1_0_9, 9_4_7_4, 1_2_9_6, 1_0_7, 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=_lowerCAmelCase , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A ( A__ , unittest.TestCase ): UpperCamelCase_ : Optional[int] =PegasusTokenizer UpperCamelCase_ : int =PegasusTokenizerFast UpperCamelCase_ : Optional[Any] =True UpperCamelCase_ : Union[str, Any] =True def _A (self ): super().setUp() # We have a SentencePiece fixture for testing __lowercase= PegasusTokenizer(_lowerCAmelCase , offset=0 , mask_token_sent=_lowerCAmelCase , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _A (self ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _A (self , **lowerCAmelCase ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def _A (self , lowerCAmelCase ): return ("This is a test", "This is a test") def _A (self ): __lowercase= self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase= self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase= ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowercase= rust_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] __lowercase= py_tokenizer([raw_input_str] , return_tensors=_lowerCAmelCase , add_special_tokens=_lowerCAmelCase ).input_ids[0] self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) @require_torch def _A (self ): __lowercase= ['This is going to be way too long.' * 1_0_0_0, 'short example'] __lowercase= ['not super long but more than 5 tokens', 'tiny'] __lowercase= self._large_tokenizer(_lowerCAmelCase , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors='pt' ) __lowercase= self._large_tokenizer( text_target=_lowerCAmelCase , max_length=5 , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4_0_9_6) assert batch.attention_mask.shape == (2, 4_0_9_6) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCAmelCase ) == 2 # input_ids, attention_mask. def _A (self ): __lowercase= ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowercase= self._large_tokenizer(_lowerCAmelCase ).input_ids self.assertListEqual( _lowerCAmelCase , [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1] , )
295
'''simple docstring''' import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __UpperCAmelCase : '''simple docstring''' def __init__(self : Tuple , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : int=13 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : Dict=2 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : Dict=16 , _lowerCAmelCase : str=[1, 2, 1] , _lowerCAmelCase : List[Any]=[2, 2, 4] , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Any=2.0 , _lowerCAmelCase : Any=True , _lowerCAmelCase : int=0.0 , _lowerCAmelCase : List[Any]=0.0 , _lowerCAmelCase : List[Any]=0.1 , _lowerCAmelCase : List[str]="gelu" , _lowerCAmelCase : Optional[Any]=False , _lowerCAmelCase : str=True , _lowerCAmelCase : List[str]=0.02 , _lowerCAmelCase : Dict=1e-5 , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=None , _lowerCAmelCase : Optional[int]=True , _lowerCAmelCase : Dict=10 , _lowerCAmelCase : int=8 , ): A = parent A = batch_size A = image_size A = patch_size A = num_channels A = embed_dim A = depths A = num_heads A = window_size A = mlp_ratio A = qkv_bias A = hidden_dropout_prob A = attention_probs_dropout_prob A = drop_path_rate A = hidden_act A = use_absolute_embeddings A = patch_norm A = layer_norm_eps A = initializer_range A = is_training A = scope A = use_labels A = type_sequence_label_size A = encoder_stride def A (self : Dict ): A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A = None if self.use_labels: A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) A = self.get_config() return config, pixel_values, labels def A (self : Optional[Any] ): return SwinvaConfig( 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 , ) def A (self : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] ): A = SwinvaModel(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) A = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A = 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 A (self : Tuple , _lowerCAmelCase : Dict , _lowerCAmelCase : int , _lowerCAmelCase : Optional[int] ): A = SwinvaForMaskedImageModeling(config=_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A = 1 A = SwinvaForMaskedImageModeling(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A = model(_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def A (self : List[str] , _lowerCAmelCase : Any , _lowerCAmelCase : Dict , _lowerCAmelCase : Any ): A = self.type_sequence_label_size A = SwinvaForImageClassification(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() A = model(_lowerCAmelCase , labels=_lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A (self : Union[str, Any] ): A = self.prepare_config_and_inputs() A , A , A = config_and_inputs A = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase ( A__ , A__ , unittest.TestCase ): '''simple docstring''' __lowerCAmelCase = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) __lowerCAmelCase = ( {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification} if is_torch_available() else {} ) __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False __lowerCAmelCase = False def A (self : Any ): A = SwinvaModelTester(self ) A = ConfigTester(self , config_class=_lowerCAmelCase , embed_dim=37 ) def A (self : Dict ): 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 A (self : int ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCAmelCase ) @unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0.""" ) def A (self : Dict ): pass @unittest.skip(reason="""Swinv2 does not use inputs_embeds""" ) def A (self : Optional[int] ): pass def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) A = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) ) def A (self : Optional[int] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A = model_class(_lowerCAmelCase ) A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A = [*signature.parameters.keys()] A = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , _lowerCAmelCase ) def A (self : int ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = True for model_class in self.all_model_classes: A = True A = False A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions A = len(self.model_tester.depths ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] A = True A = config.window_size**2 A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) A = len(_lowerCAmelCase ) # Check attention is always last and order is fine A = True A = True A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) if hasattr(self.model_tester , """num_hidden_states_types""" ): A = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A = 2 self.assertEqual(out_len + added_hidden_states , len(_lowerCAmelCase ) ) A = outputs.attentions self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def A (self : List[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] ): A = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() with torch.no_grad(): A = model(**self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase ) ) A = outputs.hidden_states A = getattr( self.model_tester , """expected_num_hidden_layers""" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) # Swinv2 has a different seq_length A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = (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] , ) A = outputs.reshaped_hidden_states self.assertEqual(len(_lowerCAmelCase ) , _lowerCAmelCase ) A , A , A , A = reshaped_hidden_states[0].shape A = ( reshaped_hidden_states[0].view(_lowerCAmelCase , _lowerCAmelCase , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def A (self : Tuple ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = ( 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: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) def A (self : List[str] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = 3 A = ( 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) ) A = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A = True self.check_hidden_states_output(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , (padded_height, padded_width) ) def A (self : Optional[int] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase ) def A (self : Union[str, Any] ): A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase ) @slow def A (self : Optional[Any] ): for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A = SwinvaModel.from_pretrained(_lowerCAmelCase ) self.assertIsNotNone(_lowerCAmelCase ) def A (self : Optional[Any] ): A , A = self.model_tester.prepare_config_and_inputs_for_common() A = _config_zero_init(_lowerCAmelCase ) for model_class in self.all_model_classes: A = model_class(config=_lowerCAmelCase ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @require_vision @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def A (self : List[str] ): return ( AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ) if is_vision_available() else None ) @slow def A (self : List[str] ): A = SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256""" ).to( _lowerCAmelCase ) A = self.default_image_processor A = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) A = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" ).to(_lowerCAmelCase ) # forward pass with torch.no_grad(): A = model(**_lowerCAmelCase ) # verify the logits A = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , _lowerCAmelCase ) A = torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(_lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1e-4 ) )
258
0
def a__ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(__UpperCamelCase , n - 1 , __UpperCamelCase ) * a) % mod else: SCREAMING_SNAKE_CASE_ = binary_exponentiation(__UpperCamelCase , n / 2 , __UpperCamelCase ) return (b * b) % mod # a prime number A : int = 7_01 A : Tuple = 10_00_00_00_00 A : List[str] = 10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" def get_matched_characters(UpperCAmelCase , UpperCAmelCase ) -> str: A = [] A = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): A = int(max(0 , i - limit ) ) A = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(UpperCAmelCase ) A = f"""{_stra[0:_stra.index(UpperCAmelCase )]} {_stra[_stra.index(UpperCAmelCase ) + 1:]}""" return "".join(UpperCAmelCase ) # matching characters A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = get_matched_characters(UpperCAmelCase , UpperCAmelCase ) A = len(UpperCAmelCase ) # transposition A = ( len([(ca, ca) for ca, ca in zip(UpperCAmelCase , UpperCAmelCase ) if ca != ca] ) // 2 ) if not match_count: A = 0.0 else: A = ( 1 / 3 * ( match_count / len(UpperCAmelCase ) + match_count / len(UpperCAmelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
258
0
from typing import Union import fire import torch from tqdm import tqdm def snake_case ( snake_case__ :Union[str, Any] , snake_case__ :List[Any] = "cpu" , snake_case__ :Optional[int] = None) -> None: _A = torch.load(snake_case__ , map_location=snake_case__) for k, v in tqdm(state_dict.items()): if not isinstance(snake_case__ , torch.Tensor): raise TypeError("""FP16 conversion only works on paths that are saved state dicts, like pytorch_model.bin""") _A = v.half() if save_path is None: # overwrite src_path _A = src_path torch.save(snake_case__ , snake_case__) if __name__ == "__main__": fire.Fire(convert)
180
'''simple docstring''' import datasets from .evaluate import evaluate _lowerCamelCase : List[str] = '\\n@article{hendrycks2021cuad,\n title={CUAD: An Expert-Annotated NLP Dataset for Legal Contract Review},\n author={Dan Hendrycks and Collin Burns and Anya Chen and Spencer Ball},\n journal={arXiv preprint arXiv:2103.06268},\n year={2021}\n}\n' _lowerCamelCase : List[Any] = '\nThis metric wrap the official scoring script for version 1 of the Contract\nUnderstanding Atticus Dataset (CUAD).\nContract Understanding Atticus Dataset (CUAD) v1 is a corpus of more than 13,000 labels in 510\ncommercial legal contracts that have been manually labeled to identify 41 categories of important\nclauses that lawyers look for when reviewing contracts in connection with corporate transactions.\n' _lowerCamelCase : Dict = '\nComputes CUAD scores (EM, F1, AUPR, Precision@80%Recall, and Precision@90%Recall).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': list of possible texts for the answer, as a list of strings\n depending on a threshold on the confidence probability of each prediction.\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the CUAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\n \'aupr\': Area Under the Precision-Recall curve\n \'prec_at_80_recall\': Precision at 80% recall\n \'prec_at_90_recall\': Precision at 90% recall\nExamples:\n >>> predictions = [{\'prediction_text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\'], \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> references = [{\'answers\': {\'answer_start\': [143, 49], \'text\': [\'The seller:\', \'The buyer/End-User: Shenzhen LOHAS Supply Chain Management Co., Ltd.\']}, \'id\': \'LohaCompanyltd_20191209_F-1_EX-10.16_11917878_EX-10.16_Supply Agreement__Parties\'}]\n >>> cuad_metric = datasets.load_metric("cuad")\n >>> results = cuad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0, \'aupr\': 0.0, \'prec_at_80_recall\': 1.0, \'prec_at_90_recall\': 1.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def A (self : int ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": { """id""": datasets.Value("""string""" ), """prediction_text""": datasets.features.Sequence(datasets.Value("""string""" ) ), }, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://www.atticusprojectai.org/cuad"""] , reference_urls=["""https://www.atticusprojectai.org/cuad"""] , ) def A (self : Dict , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ): A = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} A = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] A = evaluate(dataset=_lowerCAmelCase , predictions=_lowerCAmelCase ) return score
258
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ : Optional[int] = { 'configuration_upernet': ['UperNetConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Union[str, Any] = [ 'UperNetForSemanticSegmentation', 'UperNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_upernet import UperNetConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_upernet import UperNetForSemanticSegmentation, UperNetPreTrainedModel else: import sys a__ : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Optional import pandas as pd import pyarrow as pa import datasets from datasets.table import table_cast @dataclass class __UpperCAmelCase ( datasets.BuilderConfig ): '''simple docstring''' __lowerCAmelCase = None class __UpperCAmelCase ( datasets.ArrowBasedBuilder ): '''simple docstring''' __lowerCAmelCase = PandasConfig def A (self : Tuple ): return datasets.DatasetInfo(features=self.config.features ) def A (self : Optional[int] , _lowerCAmelCase : List[Any] ): if not self.config.data_files: raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) A = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCAmelCase , (str, list, tuple) ): A = data_files if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"""files""": files} )] A = [] for split_name, files in data_files.items(): if isinstance(_lowerCAmelCase , _lowerCAmelCase ): A = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive A = [dl_manager.iter_files(_lowerCAmelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCAmelCase , gen_kwargs={"""files""": files} ) ) return splits def A (self : Dict , _lowerCAmelCase : pa.Table ): if self.config.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example A = table_cast(_lowerCAmelCase , self.config.features.arrow_schema ) return pa_table def A (self : List[Any] , _lowerCAmelCase : Optional[Any] ): for i, file in enumerate(itertools.chain.from_iterable(_lowerCAmelCase ) ): with open(_lowerCAmelCase , """rb""" ) as f: A = pa.Table.from_pandas(pd.read_pickle(_lowerCAmelCase ) ) yield i, self._cast_table(_lowerCAmelCase )
258
0
import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[Any] ) -> Dict: return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Any ) -> List[str]: __lowercase = create_tensor(SCREAMING_SNAKE_CASE ) __lowercase = gather(SCREAMING_SNAKE_CASE ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] ) -> Any: __lowercase = [state.process_index] __lowercase = gather_object(SCREAMING_SNAKE_CASE ) assert len(SCREAMING_SNAKE_CASE ) == state.num_processes, F"""{gathered_obj}, {len(SCREAMING_SNAKE_CASE )} != {state.num_processes}""" assert gathered_obj == list(range(state.num_processes ) ), F"""{gathered_obj} != {list(range(state.num_processes ) )}""" def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Dict ) -> Union[str, Any]: __lowercase = create_tensor(SCREAMING_SNAKE_CASE ) __lowercase = broadcast(SCREAMING_SNAKE_CASE ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : List[str] ) -> Union[str, Any]: if state.is_main_process: __lowercase = torch.arange(state.num_processes + 1 ).to(state.device ) else: __lowercase = torch.arange(state.num_processes ).to(state.device ) __lowercase = pad_across_processes(SCREAMING_SNAKE_CASE ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> int: if state.num_processes != 2: return __lowercase = create_tensor(SCREAMING_SNAKE_CASE ) __lowercase = reduce(SCREAMING_SNAKE_CASE , 'sum' ) __lowercase = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), F"""{reduced_tensor} != {truth_tensor}""" def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] ) -> List[Any]: if state.num_processes != 2: return __lowercase = create_tensor(SCREAMING_SNAKE_CASE ) __lowercase = reduce(SCREAMING_SNAKE_CASE , 'mean' ) __lowercase = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ), F"""{reduced_tensor} != {truth_tensor}""" def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : str ) -> Dict: main() def __SCREAMING_SNAKE_CASE ( ) -> Optional[int]: __lowercase = PartialState() state.print(F"""State: {state}""" ) state.print('testing gather' ) test_gather(SCREAMING_SNAKE_CASE ) state.print('testing gather_object' ) test_gather_object(SCREAMING_SNAKE_CASE ) state.print('testing broadcast' ) test_broadcast(SCREAMING_SNAKE_CASE ) state.print('testing pad_across_processes' ) test_pad_across_processes(SCREAMING_SNAKE_CASE ) state.print('testing reduce_sum' ) test_reduce_sum(SCREAMING_SNAKE_CASE ) state.print('testing reduce_mean' ) test_reduce_mean(SCREAMING_SNAKE_CASE ) if __name__ == "__main__": main()
325
'''simple docstring''' from collections import Counter from timeit import timeit def __a ( UpperCAmelCase = "" , ) ->bool: """simple docstring""" return sum(c % 2 for c in Counter(input_str.replace(""" """ , """""" ).lower() ).values() ) < 2 def __a ( UpperCAmelCase = "" ) ->bool: """simple docstring""" if len(UpperCAmelCase ) == 0: return True A = input_str.replace(""" """ , """""" ).lower() # character_freq_dict: Stores the frequency of every character in the input string A = {} for character in lower_case_input_str: A = character_freq_dict.get(UpperCAmelCase , 0 ) + 1 A = 0 for character_count in character_freq_dict.values(): if character_count % 2: odd_char += 1 if odd_char > 1: return False return True def __a ( UpperCAmelCase = "" ) ->None: """simple docstring""" print("""\nFor string = """ , UpperCAmelCase , """:""" ) print( """> can_string_be_rearranged_as_palindrome_counter()""" , """\tans =""" , can_string_be_rearranged_as_palindrome_counter(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome_counter(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) print( """> can_string_be_rearranged_as_palindrome()""" , """\tans =""" , can_string_be_rearranged_as_palindrome(UpperCAmelCase ) , """\ttime =""" , timeit( """z.can_string_be_rearranged_as_palindrome(z.check_str)""" , setup="""import __main__ as z""" , ) , """seconds""" , ) if __name__ == "__main__": _lowerCamelCase : Any = input( 'Enter string to determine if it can be rearranged as a palindrome or not: ' ).strip() benchmark(check_str) _lowerCamelCase : Any = can_string_be_rearranged_as_palindrome_counter(check_str) print(f"{check_str} can {'' if status else 'not '}be rearranged as a palindrome")
258
0
def _UpperCAmelCase ( snake_case ): """simple docstring""" return number & 1 == 0 if __name__ == "__main__": import doctest doctest.testmod()
82
'''simple docstring''' import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase : Optional[Any] = logging.get_logger(__name__) _lowerCamelCase : Optional[Any] = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = '''encodec''' def __init__(self : List[Any] , _lowerCAmelCase : Union[str, Any]=[1.5, 3.0, 6.0, 12.0, 24.0] , _lowerCAmelCase : List[str]=2_4000 , _lowerCAmelCase : List[str]=1 , _lowerCAmelCase : List[str]=False , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[int]=None , _lowerCAmelCase : Dict=128 , _lowerCAmelCase : Any=32 , _lowerCAmelCase : List[Any]=1 , _lowerCAmelCase : int=[8, 5, 4, 2] , _lowerCAmelCase : Any="weight_norm" , _lowerCAmelCase : List[str]=7 , _lowerCAmelCase : int=7 , _lowerCAmelCase : Any=3 , _lowerCAmelCase : int=2 , _lowerCAmelCase : str=True , _lowerCAmelCase : str="reflect" , _lowerCAmelCase : Optional[int]=2 , _lowerCAmelCase : List[Any]=2 , _lowerCAmelCase : Tuple=1.0 , _lowerCAmelCase : Tuple=1024 , _lowerCAmelCase : str=None , _lowerCAmelCase : Dict=True , **_lowerCAmelCase : List[str] , ): A = target_bandwidths A = sampling_rate A = audio_channels A = normalize A = chunk_length_s A = overlap A = hidden_size A = num_filters A = num_residual_layers A = upsampling_ratios A = norm_type A = kernel_size A = last_kernel_size A = residual_kernel_size A = dilation_growth_rate A = use_causal_conv A = pad_mode A = compress A = num_lstm_layers A = trim_right_ratio A = codebook_size A = codebook_dim if codebook_dim is not None else hidden_size A = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**_lowerCAmelCase ) @property def A (self : List[Any] ): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def A (self : Union[str, Any] ): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def A (self : Any ): A = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def A (self : List[str] ): return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
258
0
import json import logging import os import re import sys from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union import datasets import numpy as np import torch import torchaudio from packaging import version from torch import nn import transformers from transformers import ( HfArgumentParser, Trainer, TrainingArguments, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaForCTC, WavaVecaProcessor, is_apex_available, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process if is_apex_available(): from apex import amp if version.parse(version.parse(torch.__version__).base_version) >= version.parse("""1.6"""): __UpperCamelCase : List[str] = True from torch.cuda.amp import autocast __UpperCamelCase : str = logging.getLogger(__name__) def a_ ( _A=None , _A=None ) -> Tuple: """simple docstring""" return field(default_factory=lambda: default , metadata=_A ) @dataclass class __SCREAMING_SNAKE_CASE: _UpperCAmelCase = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) _UpperCAmelCase = field( default=A__ , metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} , ) _UpperCAmelCase = field( default=A__ , metadata={"help": "Whether to freeze the feature extractor layers of the model."} ) _UpperCAmelCase = field( default=0.1 , metadata={"help": "The dropout ratio for the attention probabilities."} ) _UpperCAmelCase = field( default=0.1 , metadata={"help": "The dropout ratio for activations inside the fully connected layer."} ) _UpperCAmelCase = field( default=0.1 , metadata={ "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler." } , ) _UpperCAmelCase = field( default=0.1 , metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."} , ) _UpperCAmelCase = field( default=0.0_5 , metadata={ "help": ( "Propability of each feature vector along the time axis to be chosen as the start of the vector" "span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature" "vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``." ) } , ) _UpperCAmelCase = field(default=0.0 , metadata={"help": "The LayerDrop probability."} ) @dataclass class __SCREAMING_SNAKE_CASE: _UpperCAmelCase = field( default=A__ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) _UpperCAmelCase = field( default="train+validation" , metadata={ "help": "The name of the training data set split to use (via the datasets library). Defaults to \'train\'" } , ) _UpperCAmelCase = field( default=A__ , metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) _UpperCAmelCase = field( default=A__ , metadata={"help": "The number of processes to use for the preprocessing."} , ) _UpperCAmelCase = field( default=A__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) _UpperCAmelCase = field( default=A__ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) } , ) _UpperCAmelCase = list_field( default=[",", "?", ".", "!", "-", ";", ":", "\"\"", "%", "\'", "\"", "�"] , metadata={"help": "A list of characters to remove from the transcripts."} , ) @dataclass class __SCREAMING_SNAKE_CASE: _UpperCAmelCase = 4_2 _UpperCAmelCase = True _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None _UpperCAmelCase = None def __call__( self: List[str] , UpperCamelCase: List[Dict[str, Union[List[int], torch.Tensor]]] ) -> Optional[Any]: # split inputs and labels since they have to be of different lenghts and need # different padding methods snake_case__ = [{'input_values': feature['input_values']} for feature in features] snake_case__ = [{'input_ids': feature['labels']} for feature in features] snake_case__ = self.processor.pad( _lowerCAmelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors='pt' , ) snake_case__ = self.processor.pad( labels=_lowerCAmelCase , padding=self.padding , max_length=self.max_length_labels , pad_to_multiple_of=self.pad_to_multiple_of_labels , return_tensors='pt' , ) # replace padding with -100 to ignore loss correctly snake_case__ = labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1 ) , -1_00 ) snake_case__ = labels return batch class __SCREAMING_SNAKE_CASE( A__ ): def lowerCAmelCase_ ( self: Tuple , UpperCamelCase: nn.Module , UpperCamelCase: Dict[str, Union[torch.Tensor, Any]] ) -> Optional[Any]: model.train() snake_case__ = self._prepare_inputs(_lowerCAmelCase ) if self.use_amp: with autocast(): snake_case__ = self.compute_loss(_lowerCAmelCase , _lowerCAmelCase ) else: snake_case__ = self.compute_loss(_lowerCAmelCase , _lowerCAmelCase ) if self.args.n_gpu > 1: if model.module.config.ctc_loss_reduction == "mean": snake_case__ = loss.mean() elif model.module.config.ctc_loss_reduction == "sum": snake_case__ = loss.sum() / (inputs['labels'] >= 0).sum() else: raise ValueError(F'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']''' ) if self.args.gradient_accumulation_steps > 1: snake_case__ = loss / self.args.gradient_accumulation_steps if self.use_amp: self.scaler.scale(_lowerCAmelCase ).backward() elif self.use_apex: with amp.scale_loss(_lowerCAmelCase , self.optimizer ) as scaled_loss: scaled_loss.backward() elif self.deepspeed: self.deepspeed.backward(_lowerCAmelCase ) else: loss.backward() return loss.detach() def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case__ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. snake_case__ , snake_case__ , snake_case__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: snake_case__ , snake_case__ , snake_case__ = parser.parse_args_into_dataclasses() # Detecting last checkpoint. snake_case__ = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: snake_case__ = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + f'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , _A ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: snake_case__ = datasets.load_dataset( 'common_voice' , data_args.dataset_config_name , split=data_args.train_split_name ) snake_case__ = datasets.load_dataset('common_voice' , data_args.dataset_config_name , split='test' ) # Create and save tokenizer snake_case__ = f'''[{''.join(data_args.chars_to_ignore )}]''' def remove_special_characters(_A ): snake_case__ = re.sub(_A , '' , batch['sentence'] ).lower() + ' ' return batch snake_case__ = train_dataset.map(_A , remove_columns=['sentence'] ) snake_case__ = eval_dataset.map(_A , remove_columns=['sentence'] ) def extract_all_chars(_A ): snake_case__ = ' '.join(batch['text'] ) snake_case__ = list(set(_A ) ) return {"vocab": [vocab], "all_text": [all_text]} snake_case__ = train_dataset.map( _A , batched=_A , batch_size=-1 , keep_in_memory=_A , remove_columns=train_dataset.column_names , ) snake_case__ = train_dataset.map( _A , batched=_A , batch_size=-1 , keep_in_memory=_A , remove_columns=eval_dataset.column_names , ) snake_case__ = list(set(vocab_train['vocab'][0] ) | set(vocab_test['vocab'][0] ) ) snake_case__ = {v: k for k, v in enumerate(_A )} snake_case__ = vocab_dict[' '] del vocab_dict[" "] snake_case__ = len(_A ) snake_case__ = len(_A ) with open('vocab.json' , 'w' ) as vocab_file: json.dump(_A , _A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. snake_case__ = WavaVecaCTCTokenizer( 'vocab.json' , unk_token='[UNK]' , pad_token='[PAD]' , word_delimiter_token='|' , ) snake_case__ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0.0 , do_normalize=_A , return_attention_mask=_A ) snake_case__ = WavaVecaProcessor(feature_extractor=_A , tokenizer=_A ) snake_case__ = WavaVecaForCTC.from_pretrained( model_args.model_name_or_path , cache_dir=model_args.cache_dir , activation_dropout=model_args.activation_dropout , attention_dropout=model_args.attention_dropout , hidden_dropout=model_args.hidden_dropout , feat_proj_dropout=model_args.feat_proj_dropout , mask_time_prob=model_args.mask_time_prob , gradient_checkpointing=training_args.gradient_checkpointing , layerdrop=model_args.layerdrop , ctc_loss_reduction='mean' , pad_token_id=processor.tokenizer.pad_token_id , vocab_size=len(processor.tokenizer ) , ) if data_args.max_train_samples is not None: snake_case__ = min(len(_A ) , data_args.max_train_samples ) snake_case__ = train_dataset.select(range(_A ) ) if data_args.max_val_samples is not None: snake_case__ = eval_dataset.select(range(data_args.max_val_samples ) ) snake_case__ = torchaudio.transforms.Resample(48000 , 16000 ) # Preprocessing the datasets. # We need to read the aduio files as arrays and tokenize the targets. def speech_file_to_array_fn(_A ): snake_case__ , snake_case__ = torchaudio.load(batch['path'] ) snake_case__ = resampler(_A ).squeeze().numpy() snake_case__ = 16000 snake_case__ = batch['text'] return batch snake_case__ = train_dataset.map( _A , remove_columns=train_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) snake_case__ = eval_dataset.map( _A , remove_columns=eval_dataset.column_names , num_proc=data_args.preprocessing_num_workers , ) def prepare_dataset(_A ): # check that all files have the correct sampling rate assert ( len(set(batch['sampling_rate'] ) ) == 1 ), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.''' snake_case__ = processor( audio=batch['speech'] , text=batch['target_text'] , sampling_rate=batch['sampling_rate'][0] ) batch.update(_A ) return batch snake_case__ = train_dataset.map( _A , remove_columns=train_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_A , num_proc=data_args.preprocessing_num_workers , ) snake_case__ = eval_dataset.map( _A , remove_columns=eval_dataset.column_names , batch_size=training_args.per_device_train_batch_size , batched=_A , num_proc=data_args.preprocessing_num_workers , ) # Metric snake_case__ = datasets.load_metric('wer' ) def compute_metrics(_A ): snake_case__ = pred.predictions snake_case__ = np.argmax(_A , axis=-1 ) snake_case__ = processor.tokenizer.pad_token_id snake_case__ = processor.batch_decode(_A ) # we do not want to group tokens when computing the metrics snake_case__ = processor.batch_decode(pred.label_ids , group_tokens=_A ) snake_case__ = wer_metric.compute(predictions=_A , references=_A ) return {"wer": wer} if model_args.freeze_feature_extractor: model.freeze_feature_extractor() # Data collator snake_case__ = DataCollatorCTCWithPadding(processor=_A , padding=_A ) # Initialize our Trainer snake_case__ = CTCTrainer( model=_A , data_collator=_A , args=_A , compute_metrics=_A , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , tokenizer=processor.feature_extractor , ) # Training if training_args.do_train: if last_checkpoint is not None: snake_case__ = last_checkpoint elif os.path.isdir(model_args.model_name_or_path ): snake_case__ = model_args.model_name_or_path else: snake_case__ = None # Save the feature_extractor and the tokenizer if is_main_process(training_args.local_rank ): processor.save_pretrained(training_args.output_dir ) snake_case__ = trainer.train(resume_from_checkpoint=_A ) trainer.save_model() snake_case__ = train_result.metrics snake_case__ = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(_A ) ) snake_case__ = min(_A , len(_A ) ) trainer.log_metrics('train' , _A ) trainer.save_metrics('train' , _A ) trainer.save_state() # Evaluation snake_case__ = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) snake_case__ = trainer.evaluate() snake_case__ = data_args.max_val_samples if data_args.max_val_samples is not None else len(_A ) snake_case__ = min(_A , len(_A ) ) trainer.log_metrics('eval' , _A ) trainer.save_metrics('eval' , _A ) return results if __name__ == "__main__": main()
307
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available _lowerCamelCase : Dict = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : List[str] = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Union[str, Any] = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys _lowerCamelCase : Optional[int] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
258
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase : Any = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Dict = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : int = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Optional[Any] = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase : Union[str, Any] = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
20
'''simple docstring''' import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : str ): A = """ylacombe/bark-small""" A = tempfile.mkdtemp() A = """en_speaker_1""" A = """This is a test string""" A = """speaker_embeddings_path.json""" A = """speaker_embeddings""" def A (self : Optional[Any] , **_lowerCAmelCase : Any ): return AutoTokenizer.from_pretrained(self.checkpoint , **_lowerCAmelCase ) def A (self : Dict ): shutil.rmtree(self.tmpdirname ) def A (self : Optional[Any] ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) processor.save_pretrained(self.tmpdirname ) A = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def A (self : int ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) A = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) A = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token="""(BOS)""" , eos_token="""(EOS)""" , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def A (self : Union[str, Any] ): A = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) A = 35 A = 2 A = 8 A = { """semantic_prompt""": np.ones(_lowerCAmelCase ), """coarse_prompt""": np.ones((nb_codebooks_coarse, seq_len) ), """fine_prompt""": np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from npz file A = os.path.join(self.tmpdirname , """file.npz""" ) np.savez(_lowerCAmelCase , **_lowerCAmelCase ) A = processor(text=self.input_string , voice_preset=_lowerCAmelCase ) A = inputs["""history_prompt"""] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(_lowerCAmelCase , np.array([] ) ).tolist() ) # test loading voice preset from the hub A = processor(text=self.input_string , voice_preset=self.voice_preset ) def A (self : str ): A = self.get_tokenizer() A = BarkProcessor(tokenizer=_lowerCAmelCase ) A = processor(text=self.input_string ) A = tokenizer( self.input_string , padding="""max_length""" , max_length=256 , add_special_tokens=_lowerCAmelCase , return_attention_mask=_lowerCAmelCase , return_token_type_ids=_lowerCAmelCase , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
258
0
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 ) -> tuple: return (data["data"], data["target"]) def lowerCamelCase__ ( a , a , a ) -> np.ndarray: _A: Tuple = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(a , a ) # Predict target for test data _A: Optional[Any] = xgb.predict(a ) _A: str = predictions.reshape(len(a ) , 1 ) return predictions def lowerCamelCase__ ( ) -> None: _A: List[Any] = fetch_california_housing() _A , _A: Optional[int] = data_handling(a ) _A , _A , _A , _A: Optional[int] = train_test_split( a , a , test_size=0.25 , random_state=1 ) _A: Any = 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()
121
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan _lowerCamelCase : List[Any] = 6_3_7_8_1_3_7.0 _lowerCamelCase : List[Any] = 6_3_5_6_7_5_2.3_1_4_2_4_5 _lowerCamelCase : Optional[int] = 637_8137 def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->float: """simple docstring""" A = (AXIS_A - AXIS_B) / AXIS_A A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = atan((1 - flattening) * tan(radians(UpperCAmelCase ) ) ) A = radians(UpperCAmelCase ) A = radians(UpperCAmelCase ) # Equation A = sin((phi_a - phi_a) / 2 ) A = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda A = sqrt(sin_sq_phi + (cos(UpperCAmelCase ) * cos(UpperCAmelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(UpperCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
258
0
'''simple docstring''' from __future__ import annotations import collections import pprint from pathlib import Path def _UpperCamelCase ( UpperCamelCase__ ): return "".join(sorted(UpperCamelCase__ ) ) def _UpperCamelCase ( UpperCamelCase__ ): return word_by_signature[signature(UpperCamelCase__ )] __A =Path(__file__).parent.joinpath('words.txt').read_text(encoding='utf-8') __A =sorted({word.strip().lower() for word in data.splitlines()}) __A =collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": __A ={word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('anagrams.txt', 'w') as file: file.write('all_anagrams = \n ') file.write(pprint.pformat(all_anagrams))
163
'''simple docstring''' import os import sys import unittest _lowerCamelCase : Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) _lowerCamelCase : str = os.path.join('tests', 'models', 'bert', 'test_modeling_bert.py') _lowerCamelCase : Tuple = os.path.join('tests', 'models', 'blip', 'test_modeling_blip.py') class __UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def A (self : Any ): A = get_test_to_tester_mapping(_lowerCAmelCase ) A = get_test_to_tester_mapping(_lowerCAmelCase ) A = {"""BertModelTest""": """BertModelTester"""} A = { """BlipModelTest""": """BlipModelTester""", """BlipTextImageModelTest""": """BlipTextImageModelsModelTester""", """BlipTextModelTest""": """BlipTextModelTester""", """BlipTextRetrievalModelTest""": """BlipTextRetrievalModelTester""", """BlipVQAModelTest""": """BlipVQAModelTester""", """BlipVisionModelTest""": """BlipVisionModelTester""", } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : str ): A = get_model_to_test_mapping(_lowerCAmelCase ) A = get_model_to_test_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTest"""], """BertForMultipleChoice""": ["""BertModelTest"""], """BertForNextSentencePrediction""": ["""BertModelTest"""], """BertForPreTraining""": ["""BertModelTest"""], """BertForQuestionAnswering""": ["""BertModelTest"""], """BertForSequenceClassification""": ["""BertModelTest"""], """BertForTokenClassification""": ["""BertModelTest"""], """BertLMHeadModel""": ["""BertModelTest"""], """BertModel""": ["""BertModelTest"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelTest"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTest"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTest"""], """BlipModel""": ["""BlipModelTest"""], """BlipTextModel""": ["""BlipTextModelTest"""], """BlipVisionModel""": ["""BlipVisionModelTest"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): A = get_model_to_tester_mapping(_lowerCAmelCase ) A = get_model_to_tester_mapping(_lowerCAmelCase ) A = { """BertForMaskedLM""": ["""BertModelTester"""], """BertForMultipleChoice""": ["""BertModelTester"""], """BertForNextSentencePrediction""": ["""BertModelTester"""], """BertForPreTraining""": ["""BertModelTester"""], """BertForQuestionAnswering""": ["""BertModelTester"""], """BertForSequenceClassification""": ["""BertModelTester"""], """BertForTokenClassification""": ["""BertModelTester"""], """BertLMHeadModel""": ["""BertModelTester"""], """BertModel""": ["""BertModelTester"""], } A = { """BlipForConditionalGeneration""": ["""BlipTextImageModelsModelTester"""], """BlipForImageTextRetrieval""": ["""BlipTextRetrievalModelTester"""], """BlipForQuestionAnswering""": ["""BlipVQAModelTester"""], """BlipModel""": ["""BlipModelTester"""], """BlipTextModel""": ["""BlipTextModelTester"""], """BlipVisionModel""": ["""BlipVisionModelTester"""], } self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(get_test_info.to_json(_lowerCAmelCase ) , _lowerCAmelCase )
258
0
'''simple docstring''' import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def snake_case_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None , )-> Any: '''simple docstring''' if attention_mask is None: _UpperCAmelCase : int = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: _UpperCAmelCase : Optional[int] = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: _UpperCAmelCase : List[str] = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=lowerCAmelCase_ ) if decoder_head_mask is None: _UpperCAmelCase : List[Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=lowerCAmelCase_ ) if cross_attn_head_mask is None: _UpperCAmelCase : Optional[Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=lowerCAmelCase_ ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class lowercase : """simple docstring""" def __init__( self ,a_ ,a_=13 ,a_=7 ,a_=True ,a_=False ,a_=99 ,a_=16 ,a_=2 ,a_=4 ,a_=4 ,a_="relu" ,a_=0.1 ,a_=0.1 ,a_=0.0 ,a_=0.0 ,a_=20 ,a_=2 ,a_=1 ,a_=0 ,) -> Optional[Any]: _UpperCAmelCase : Any = parent _UpperCAmelCase : List[str] = batch_size _UpperCAmelCase : str = seq_length _UpperCAmelCase : Tuple = is_training _UpperCAmelCase : Tuple = use_labels _UpperCAmelCase : Dict = vocab_size _UpperCAmelCase : Optional[int] = hidden_size _UpperCAmelCase : Any = num_hidden_layers _UpperCAmelCase : List[str] = num_attention_heads _UpperCAmelCase : List[Any] = intermediate_size _UpperCAmelCase : int = hidden_act _UpperCAmelCase : Optional[Any] = hidden_dropout_prob _UpperCAmelCase : Optional[int] = attention_probs_dropout_prob _UpperCAmelCase : List[str] = encoder_layerdrop _UpperCAmelCase : List[str] = decoder_layerdrop _UpperCAmelCase : Union[str, Any] = max_position_embeddings _UpperCAmelCase : Optional[int] = eos_token_id _UpperCAmelCase : Dict = pad_token_id _UpperCAmelCase : int = bos_token_id def _snake_case ( self ) -> Union[str, Any]: _UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _UpperCAmelCase : Optional[Any] = self.eos_token_id # Eos Token _UpperCAmelCase : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input _UpperCAmelCase : Dict = input_ids.clamp(self.pad_token_id + 1 ) _UpperCAmelCase : Tuple = decoder_input_ids.clamp(self.pad_token_id + 1 ) _UpperCAmelCase : Dict = self.get_config() _UpperCAmelCase : str = prepare_mam_aaa_inputs_dict(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) return config, inputs_dict def _snake_case ( self ) -> List[Any]: return MaMaaaConfig( vocab_size=self.vocab_size ,d_model=self.hidden_size ,encoder_layers=self.num_hidden_layers ,decoder_layers=self.num_hidden_layers ,encoder_attention_heads=self.num_attention_heads ,decoder_attention_heads=self.num_attention_heads ,encoder_ffn_dim=self.intermediate_size ,decoder_ffn_dim=self.intermediate_size ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,encoder_layerdrop=self.encoder_layerdrop ,decoder_layerdrop=self.decoder_layerdrop ,max_position_embeddings=self.max_position_embeddings ,eos_token_id=self.eos_token_id ,bos_token_id=self.bos_token_id ,pad_token_id=self.pad_token_id ,) def _snake_case ( self ) -> List[Any]: _UpperCAmelCase ,_UpperCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() return config, inputs_dict def _snake_case ( self ,a_ ,a_ ) -> str: _UpperCAmelCase : int = MaMaaaModel(config=_lowerCAmelCase ).get_decoder().to(_lowerCAmelCase ).eval() _UpperCAmelCase : List[Any] = inputs_dict["""input_ids"""] _UpperCAmelCase : List[Any] = inputs_dict["""attention_mask"""] _UpperCAmelCase : Dict = inputs_dict["""head_mask"""] # first forward pass _UpperCAmelCase : Optional[Any] = model(_lowerCAmelCase ,attention_mask=_lowerCAmelCase ,head_mask=_lowerCAmelCase ,use_cache=_lowerCAmelCase ) _UpperCAmelCase ,_UpperCAmelCase : Optional[int] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids _UpperCAmelCase : int = ids_tensor((self.batch_size, 3) ,config.vocab_size ) _UpperCAmelCase : Optional[int] = ids_tensor((self.batch_size, 3) ,2 ) # append to next input_ids and _UpperCAmelCase : str = torch.cat([input_ids, next_tokens] ,dim=-1 ) _UpperCAmelCase : Optional[int] = torch.cat([attention_mask, next_attn_mask] ,dim=-1 ) _UpperCAmelCase : Dict = model(_lowerCAmelCase ,attention_mask=_lowerCAmelCase )["""last_hidden_state"""] _UpperCAmelCase : Tuple = model(_lowerCAmelCase ,attention_mask=_lowerCAmelCase ,past_key_values=_lowerCAmelCase )[ """last_hidden_state""" ] # select random slice _UpperCAmelCase : str = ids_tensor((1,) ,output_from_past.shape[-1] ).item() _UpperCAmelCase : Optional[int] = output_from_no_past[:, -3:, random_slice_idx].detach() _UpperCAmelCase : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_lowerCAmelCase ,_lowerCAmelCase ,atol=1E-2 ) ) def _snake_case ( self ,a_ ,a_ ) -> int: _UpperCAmelCase : str = MaMaaaModel(config=_lowerCAmelCase ).to(_lowerCAmelCase ).eval() _UpperCAmelCase : str = model(**_lowerCAmelCase ) _UpperCAmelCase : Union[str, Any] = outputs.encoder_last_hidden_state _UpperCAmelCase : str = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase : Dict = model.get_encoder() encoder.save_pretrained(_lowerCAmelCase ) _UpperCAmelCase : List[str] = MaMaaaEncoder.from_pretrained(_lowerCAmelCase ).to(_lowerCAmelCase ) _UpperCAmelCase : Dict = encoder(inputs_dict["""input_ids"""] ,attention_mask=inputs_dict["""attention_mask"""] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3 ) with tempfile.TemporaryDirectory() as tmpdirname: _UpperCAmelCase : Any = model.get_decoder() decoder.save_pretrained(_lowerCAmelCase ) _UpperCAmelCase : Optional[Any] = MaMaaaDecoder.from_pretrained(_lowerCAmelCase ).to(_lowerCAmelCase ) _UpperCAmelCase : List[Any] = decoder( input_ids=inputs_dict["""decoder_input_ids"""] ,attention_mask=inputs_dict["""decoder_attention_mask"""] ,encoder_hidden_states=_lowerCAmelCase ,encoder_attention_mask=inputs_dict["""attention_mask"""] ,)[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3 ) @require_torch class lowercase ( A__ , A__ , A__ , unittest.TestCase ): """simple docstring""" UpperCAmelCase = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) UpperCAmelCase = (MaMaaaForConditionalGeneration,) if is_torch_available() else () UpperCAmelCase = ( { """conversational""": MaMaaaForConditionalGeneration, """feature-extraction""": MaMaaaModel, """summarization""": MaMaaaForConditionalGeneration, """text2text-generation""": MaMaaaForConditionalGeneration, """translation""": MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = False def _snake_case ( self ,a_ ,a_ ,a_ ,a_ ,a_ ) -> Tuple: if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def _snake_case ( self ) -> Tuple: _UpperCAmelCase : List[Any] = MaMaaaModelTester(self ) _UpperCAmelCase : List[str] = ConfigTester(self ,config_class=_lowerCAmelCase ) def _snake_case ( self ) -> int: self.config_tester.run_common_tests() def _snake_case ( self ) -> Dict: _UpperCAmelCase ,_UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: _UpperCAmelCase : Tuple = model_class(_lowerCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_lowerCAmelCase ) _UpperCAmelCase ,_UpperCAmelCase : List[Any] = model_class.from_pretrained(_lowerCAmelCase ,output_loading_info=_lowerCAmelCase ) self.assertEqual(info["""missing_keys"""] ,[] ) def _snake_case ( self ) -> str: _UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*_lowerCAmelCase ) def _snake_case ( self ) -> Optional[int]: _UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_lowerCAmelCase ) def _snake_case ( self ) -> Any: _UpperCAmelCase ,_UpperCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): _UpperCAmelCase : Tuple = model_class(_lowerCAmelCase ) model.to(_lowerCAmelCase ) model.eval() _UpperCAmelCase : int = copy.deepcopy(self._prepare_for_class(_lowerCAmelCase ,_lowerCAmelCase ) ) if not self.is_encoder_decoder: _UpperCAmelCase : str = inputs["""input_ids"""] del inputs["input_ids"] else: _UpperCAmelCase : str = inputs["""input_ids"""] _UpperCAmelCase : List[Any] = inputs.get("""decoder_input_ids""" ,_lowerCAmelCase ) del inputs["input_ids"] inputs.pop("""decoder_input_ids""" ,_lowerCAmelCase ) _UpperCAmelCase : List[Any] = model.get_input_embeddings() if not self.is_encoder_decoder: _UpperCAmelCase : List[str] = wte(_lowerCAmelCase ) else: _UpperCAmelCase : List[str] = wte(_lowerCAmelCase ) _UpperCAmelCase : List[str] = wte(_lowerCAmelCase ) with torch.no_grad(): model(**_lowerCAmelCase )[0] def _snake_case ( self ) -> Optional[int]: _UpperCAmelCase ,_UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() _UpperCAmelCase : Optional[int] = input_dict["""input_ids"""] _UpperCAmelCase : Dict = input_ids.ne(1 ).to(_lowerCAmelCase ) _UpperCAmelCase : List[Any] = MaMaaaForConditionalGeneration(_lowerCAmelCase ).eval().to(_lowerCAmelCase ) if torch_device == "cuda": model.half() model.generate(_lowerCAmelCase ,attention_mask=_lowerCAmelCase ) model.generate(num_beams=4 ,do_sample=_lowerCAmelCase ,early_stopping=_lowerCAmelCase ,num_return_sequences=3 ) def snake_case_ ( lowerCAmelCase_ )-> str: '''simple docstring''' return torch.tensor(lowerCAmelCase_ , dtype=torch.long , device=lowerCAmelCase_ ) A_ : List[Any] = 1e-4 @require_torch @require_sentencepiece @require_tokenizers @slow class lowercase ( unittest.TestCase ): """simple docstring""" @cached_property def _snake_case ( self ) -> Dict: return MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" ) def _snake_case ( self ) -> List[Any]: _UpperCAmelCase : Tuple = MaMaaaModel.from_pretrained("""facebook/m2m100_418M""" ).to(_lowerCAmelCase ) _UpperCAmelCase : List[str] = _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]] ) _UpperCAmelCase : List[Any] = _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]] ) _UpperCAmelCase : Dict = prepare_mam_aaa_inputs_dict(model.config ,_lowerCAmelCase ,_lowerCAmelCase ) with torch.no_grad(): _UpperCAmelCase : Any = model(**_lowerCAmelCase )[0] _UpperCAmelCase : int = torch.Size((1, 11, 1_024) ) self.assertEqual(output.shape ,_lowerCAmelCase ) # change to expected output here _UpperCAmelCase : Dict = torch.tensor( [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]] ,device=_lowerCAmelCase ) self.assertTrue(torch.allclose(output[:, :3, :3] ,_lowerCAmelCase ,atol=_lowerCAmelCase ) ) def _snake_case ( self ) -> Dict: _UpperCAmelCase : Union[str, Any] = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(_lowerCAmelCase ) # change to intended input _UpperCAmelCase : List[str] = _long_tensor([[128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38, 2]] ) _UpperCAmelCase : List[str] = _long_tensor([[2, 128_028, 98, 12, 30_527, 2_732, 159, 7_755, 61_904, 39_144, 38]] ) _UpperCAmelCase : List[str] = prepare_mam_aaa_inputs_dict(model.config ,_lowerCAmelCase ,_lowerCAmelCase ) with torch.no_grad(): _UpperCAmelCase : Optional[int] = model(**_lowerCAmelCase )[0] _UpperCAmelCase : List[str] = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape ,_lowerCAmelCase ) # change to expected output here _UpperCAmelCase : int = torch.tensor( [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]] ,device=_lowerCAmelCase ) self.assertTrue(torch.allclose(output[:, :3, :3] ,_lowerCAmelCase ,atol=_lowerCAmelCase ) ) def _snake_case ( self ) -> Union[str, Any]: _UpperCAmelCase : Optional[int] = MaMaaaForConditionalGeneration.from_pretrained("""facebook/m2m100_418M""" ).to(_lowerCAmelCase ) _UpperCAmelCase : List[str] = MaMaaaTokenizer.from_pretrained("""facebook/m2m100_418M""" ,src_lang="""fr""" ,tgt_lang="""en""" ) _UpperCAmelCase : Tuple = [ """L'affaire NSA souligne l'absence totale de débat sur le renseignement""", """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""", """Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent""" """ Fabius convoque l'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de""" """ l'ampleur de la surveillance américaine sur l'ensemble des communications en France.""", ] # The below article tests that we don't add any hypotheses outside of the top n_beams _UpperCAmelCase : str = tokenizer(_lowerCAmelCase ,padding=_lowerCAmelCase ,return_tensors="""pt""" ) _UpperCAmelCase : int = model.generate( input_ids=dct["""input_ids"""].to(_lowerCAmelCase ) ,attention_mask=dct["""attention_mask"""].to(_lowerCAmelCase ) ,num_beams=5 ,forced_bos_token_id=tokenizer.get_lang_id("""en""" ) ,) _UpperCAmelCase : Dict = [ """The NSA case highlights the total absence of intelligence debate""", """I think there are two levels of response from the French government.""", """When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.""" """ Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all""" """ communications in France.""", ] _UpperCAmelCase : int = tokenizer.batch_decode( hypotheses_batch.tolist() ,clean_up_tokenization_spaces=_lowerCAmelCase ,skip_special_tokens=_lowerCAmelCase ) assert generated == expected_en
215
'''simple docstring''' from __future__ import annotations def __a ( UpperCAmelCase , UpperCAmelCase ) ->Tuple: """simple docstring""" if len(UpperCAmelCase ) <= 1 or n <= 1: return insert_next(UpperCAmelCase , n - 1 ) rec_insertion_sort(UpperCAmelCase , n - 1 ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" if index >= len(UpperCAmelCase ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order A , A = ( collection[index], collection[index - 1], ) insert_next(UpperCAmelCase , index + 1 ) if __name__ == "__main__": _lowerCamelCase : List[Any] = input('Enter integers separated by spaces: ') _lowerCamelCase : list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
258
0
import fcntl import os import socket import torch import torch.distributed as dist def _lowerCamelCase( *lowercase__ ) -> Dict: '''simple docstring''' with open(lowercase__ , 'r' ) as fh: fcntl.flock(lowercase__ , fcntl.LOCK_EX ) try: print(*lowercase__ ) finally: fcntl.flock(lowercase__ , fcntl.LOCK_UN ) lowerCAmelCase = int(os.environ['''LOCAL_RANK''']) torch.cuda.set_device(local_rank) lowerCAmelCase = torch.device('''cuda''', local_rank) lowerCAmelCase = socket.gethostname() lowerCAmelCase = F'[{hostname}-{local_rank}]' try: # test distributed dist.init_process_group('''nccl''') dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank lowerCAmelCase = dist.get_rank() lowerCAmelCase = dist.get_world_size() printflock(F'{gpu} is OK (global rank: {rank}/{world_size})') dist.barrier() if rank == 0: printflock(F'pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}') except Exception: printflock(F'{gpu} is broken') raise
295
'''simple docstring''' import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def __a ( UpperCAmelCase ) ->Tuple: # picklable for multiprocessing """simple docstring""" return x.sum() def __a ( UpperCAmelCase ) ->int: # picklable for multiprocessing """simple docstring""" return i + 1 @dataclass class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = 42 __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def A (self : Tuple ): A = {} A = [] A = 1 A = [1, 2] A = {"""a""": 1, """b""": 2} A = {"""a""": [1, 2], """b""": [3, 4]} A = {"""a""": {"""1""": 1}, """b""": 2} A = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4} A = {} A = [] A = 2 A = [2, 3] A = {"""a""": 2, """b""": 3} A = {"""a""": [2, 3], """b""": [4, 5]} A = {"""a""": {"""1""": 2}, """b""": 3} A = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5} self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase ) , _lowerCAmelCase ) A = 2 self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) A = {"""a""": np.eye(2 ), """b""": np.zeros(3 ), """c""": np.ones(2 )} A = {"""a""": 2, """b""": 0, """c""": 2} A = { """a""": np.eye(2 ).astype(_lowerCAmelCase ), """b""": np.zeros(3 ).astype(_lowerCAmelCase ), """c""": np.ones(2 ).astype(_lowerCAmelCase ), } self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ) , _lowerCAmelCase ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_lowerCAmelCase , _lowerCAmelCase , map_numpy=_lowerCAmelCase , num_proc=_lowerCAmelCase ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(_lowerCAmelCase ): # can't pickle a local lambda map_nested(lambda _lowerCAmelCase : x + 1 , _lowerCAmelCase , num_proc=_lowerCAmelCase ) def A (self : List[Any] ): A = {"""a""": 1, """b""": 2} A = {"""a""": 3, """b""": 4} A = {"""a""": 5, """b""": 6} A = sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) ) , _lowerCAmelCase ) def A (self : Union[str, Any] ): class __UpperCAmelCase : '''simple docstring''' __lowerCAmelCase = '''bar''' A = Foo() self.assertEqual(foo.my_attr , """bar""" ) with temporary_assignment(_lowerCAmelCase , """my_attr""" , """BAR""" ): self.assertEqual(foo.my_attr , """BAR""" ) self.assertEqual(foo.my_attr , """bar""" ) @pytest.mark.parametrize( """iterable_length, num_proc, expected_num_proc""" , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Any: """simple docstring""" with patch("""datasets.utils.py_utils._single_map_nested""" ) as mock_single_map_nested, patch( """datasets.parallel.parallel.Pool""" ) as mock_multiprocessing_pool: A = {f"""{i}""": i for i in range(UpperCAmelCase )} A = map_nested(lambda UpperCAmelCase : x + 10 , UpperCAmelCase , num_proc=UpperCAmelCase , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class __UpperCAmelCase ( A__ ): '''simple docstring''' @require_tf def A (self : Dict ): import tensorflow as tf from tensorflow.keras import layers A = layers.Dense(2 ) def gen_random_output(): A = tf.random.uniform((1, 3) ) return model(_lowerCAmelCase ).numpy() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_tensorflow=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def A (self : Tuple ): import torch def gen_random_output(): A = torch.nn.Linear(3 , 2 ) A = torch.rand(1 , 3 ) return model(_lowerCAmelCase ).detach().numpy() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() with temp_seed(42 , set_pytorch=_lowerCAmelCase ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def A (self : str ): def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): A = gen_random_output() with temp_seed(42 ): A = gen_random_output() A = gen_random_output() np.testing.assert_equal(_lowerCAmelCase , _lowerCAmelCase ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize("""input_data""" , [{}] ) def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).data assert output_data == input_data @pytest.mark.parametrize( """data, expected_output""" , [ ({}, []), ([], []), ("""foo""", ["""foo"""]), (["""foo""", """bar"""], ["""foo""", """bar"""]), ([["""foo""", """bar"""]], ["""foo""", """bar"""]), ([[["""foo"""], ["""bar"""]]], ["""foo""", """bar"""]), ([[["""foo"""], """bar"""]], ["""foo""", """bar"""]), ({"""a""": 1, """b""": 2}, [1, 2]), ({"""a""": [1, 2], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[1, 2]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[[3], [4]]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [[3, 4]]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, 4]}, [1, 2, 3, 4]), ({"""a""": [[[1], [2]]], """b""": [3, [4]]}, [1, 2, 3, 4]), ({"""a""": {"""1""": 1}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": 2}, [1, 2]), ({"""a""": {"""1""": [1]}, """b""": [2]}, [1, 2]), ] , ) def __a ( UpperCAmelCase , UpperCAmelCase ) ->List[Any]: """simple docstring""" A = NestedDataStructure(UpperCAmelCase ).flatten() assert output == expected_output def __a ( ) ->Optional[Any]: """simple docstring""" A = A(x=1 , y="""foobar""" ) A = {"""x""": 1, """y""": """foobar"""} assert asdict(UpperCAmelCase ) == expected_output A = {"""a""": {"""b""": A(x=10 , y="""foo""" )}, """c""": [A(x=20 , y="""bar""" )]} A = {"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]} assert asdict(UpperCAmelCase ) == expected_output with pytest.raises(UpperCAmelCase ): asdict([1, A(x=10 , y="""foo""" )] ) def __a ( UpperCAmelCase ) ->Tuple: """simple docstring""" return text.split() def __a ( UpperCAmelCase ) ->List[str]: """simple docstring""" yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def __a ( ) ->Optional[int]: """simple docstring""" with Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: A = list(iflatmap_unordered(UpperCAmelCase , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) ) assert out.count("""hello""" ) == 10 assert out.count("""there""" ) == 10 assert len(UpperCAmelCase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: A = [] for yield_time, content in iflatmap_unordered( UpperCAmelCase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"""content""": """a"""}, {"""content""": """b"""}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(UpperCAmelCase ) assert out.count("""a""" ) == 2 assert out.count("""b""" ) == 2 assert len(UpperCAmelCase ) == 4
258
0
class lowerCamelCase : """simple docstring""" def __init__( self : int , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] ) -> Tuple: SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = None SCREAMING_SNAKE_CASE_ = graph self._normalize_graph(_lowerCAmelCase , _lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = len(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = None def __A ( self : int , __magic_name__ : Tuple , __magic_name__ : Any ) -> Any: if sources is int: SCREAMING_SNAKE_CASE_ = [sources] if sinks is int: SCREAMING_SNAKE_CASE_ = [sinks] if len(_lowerCAmelCase ) == 0 or len(_lowerCAmelCase ) == 0: return SCREAMING_SNAKE_CASE_ = sources[0] SCREAMING_SNAKE_CASE_ = sinks[0] # make fake vertex if there are more # than one source or sink if len(_lowerCAmelCase ) > 1 or len(_lowerCAmelCase ) > 1: SCREAMING_SNAKE_CASE_ = 0 for i in sources: max_input_flow += sum(self.graph[i] ) SCREAMING_SNAKE_CASE_ = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: SCREAMING_SNAKE_CASE_ = max_input_flow SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: SCREAMING_SNAKE_CASE_ = max_input_flow SCREAMING_SNAKE_CASE_ = size - 1 def __A ( self : Tuple ) -> int: if self.maximum_flow_algorithm is None: raise Exception("You need to set maximum flow algorithm before." ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def __A ( self : Optional[int] , __magic_name__ : int ) -> str: SCREAMING_SNAKE_CASE_ = algorithm(self ) class lowerCamelCase : """simple docstring""" def __init__( self : Optional[Any] , __magic_name__ : Optional[Any] ) -> int: SCREAMING_SNAKE_CASE_ = flow_network SCREAMING_SNAKE_CASE_ = flow_network.verticesCount SCREAMING_SNAKE_CASE_ = flow_network.sourceIndex SCREAMING_SNAKE_CASE_ = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that SCREAMING_SNAKE_CASE_ = flow_network.graph SCREAMING_SNAKE_CASE_ = False def __A ( self : str ) -> Dict: if not self.executed: self._algorithm() SCREAMING_SNAKE_CASE_ = True def __A ( self : Any ) -> Any: pass class lowerCamelCase (A__ ): """simple docstring""" def __init__( self : Optional[int] , __magic_name__ : Tuple ) -> List[str]: super().__init__(_lowerCAmelCase ) # use this to save your result SCREAMING_SNAKE_CASE_ = -1 def __A ( self : Optional[int] ) -> Optional[Any]: if not self.executed: raise Exception("You should execute algorithm before using its result!" ) return self.maximum_flow class lowerCamelCase (A__ ): """simple docstring""" def __init__( self : Tuple , __magic_name__ : str ) -> Union[str, Any]: super().__init__(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = [[0] * self.verticies_count for i in range(self.verticies_count )] SCREAMING_SNAKE_CASE_ = [0] * self.verticies_count SCREAMING_SNAKE_CASE_ = [0] * self.verticies_count def __A ( self : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE_ = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule SCREAMING_SNAKE_CASE_ = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list SCREAMING_SNAKE_CASE_ = 0 while i < len(_lowerCAmelCase ): SCREAMING_SNAKE_CASE_ = vertices_list[i] SCREAMING_SNAKE_CASE_ = self.heights[vertex_index] self.process_vertex(_lowerCAmelCase ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(_lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ = 0 else: i += 1 SCREAMING_SNAKE_CASE_ = sum(self.preflow[self.source_index] ) def __A ( self : Tuple , __magic_name__ : str ) -> Tuple: while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(_lowerCAmelCase , _lowerCAmelCase ) self.relabel(_lowerCAmelCase ) def __A ( self : Dict , __magic_name__ : Optional[int] , __magic_name__ : List[Any] ) -> Any: SCREAMING_SNAKE_CASE_ = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def __A ( self : Dict , __magic_name__ : List[str] ) -> Dict: SCREAMING_SNAKE_CASE_ = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): SCREAMING_SNAKE_CASE_ = self.heights[to_index] if min_height is not None: SCREAMING_SNAKE_CASE_ = min_height + 1 if __name__ == "__main__": A : Optional[int] = [0] A : int = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] A : str = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network A : Optional[Any] = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate A : Optional[int] = flow_network.find_maximum_flow() print(f"maximum flow is {maximum_flow}")
118
'''simple docstring''' def __a ( UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" return int((input_a, input_a).count(1 ) != 0 ) def __a ( ) ->None: """simple docstring""" assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
258
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) _SCREAMING_SNAKE_CASE = { 'configuration_roformer': ['ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoFormerConfig', 'RoFormerOnnxConfig'], 'tokenization_roformer': ['RoFormerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = ['RoFormerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ 'ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoFormerForCausalLM', 'RoFormerForMaskedLM', 'RoFormerForMultipleChoice', 'RoFormerForQuestionAnswering', 'RoFormerForSequenceClassification', 'RoFormerForTokenClassification', 'RoFormerLayer', 'RoFormerModel', 'RoFormerPreTrainedModel', 'load_tf_weights_in_roformer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ 'TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRoFormerForCausalLM', 'TFRoFormerForMaskedLM', 'TFRoFormerForMultipleChoice', 'TFRoFormerForQuestionAnswering', 'TFRoFormerForSequenceClassification', 'TFRoFormerForTokenClassification', 'TFRoFormerLayer', 'TFRoFormerModel', 'TFRoFormerPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ 'FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxRoFormerForMaskedLM', 'FlaxRoFormerForMultipleChoice', 'FlaxRoFormerForQuestionAnswering', 'FlaxRoFormerForSequenceClassification', 'FlaxRoFormerForTokenClassification', 'FlaxRoFormerModel', 'FlaxRoFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
180
'''simple docstring''' from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) # pylint: disable=invalid-name _lowerCamelCase : str = '\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n >>> repo = "openai/shap-e-img2img"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n >>> image = load_image(image_url).convert("RGB")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n ```\n' @dataclass class __UpperCAmelCase ( A__ ): '''simple docstring''' __lowerCAmelCase = 42 class __UpperCAmelCase ( A__ ): '''simple docstring''' def __init__(self : str , _lowerCAmelCase : PriorTransformer , _lowerCAmelCase : CLIPVisionModel , _lowerCAmelCase : CLIPImageProcessor , _lowerCAmelCase : HeunDiscreteScheduler , _lowerCAmelCase : ShapERenderer , ): super().__init__() self.register_modules( prior=_lowerCAmelCase , image_encoder=_lowerCAmelCase , image_processor=_lowerCAmelCase , scheduler=_lowerCAmelCase , renderer=_lowerCAmelCase , ) def A (self : Dict , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Any , _lowerCAmelCase : Tuple , _lowerCAmelCase : Optional[Any] ): if latents is None: A = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) A = latents.to(_lowerCAmelCase ) A = latents * scheduler.init_noise_sigma return latents def A (self : Union[str, Any] , _lowerCAmelCase : List[Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) A = torch.device(F"""cuda:{gpu_id}""" ) A = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_lowerCAmelCase , _lowerCAmelCase ) @property def A (self : Optional[Any] ): if self.device != torch.device("""meta""" ) or not hasattr(self.image_encoder , """_hf_hook""" ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_lowerCAmelCase , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def A (self : int , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any , _lowerCAmelCase : Optional[int] , ): if isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , torch.Tensor ): A = torch.cat(_lowerCAmelCase , axis=0 ) if image[0].ndim == 4 else torch.stack(_lowerCAmelCase , axis=0 ) if not isinstance(_lowerCAmelCase , torch.Tensor ): A = self.image_processor(_lowerCAmelCase , return_tensors="""pt""" ).pixel_values[0].unsqueeze(0 ) A = image.to(dtype=self.image_encoder.dtype , device=_lowerCAmelCase ) A = self.image_encoder(_lowerCAmelCase )["""last_hidden_state"""] A = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 A = image_embeds.repeat_interleave(_lowerCAmelCase , dim=0 ) if do_classifier_free_guidance: A = torch.zeros_like(_lowerCAmelCase ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes A = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_lowerCAmelCase ) def __call__(self : List[Any] , _lowerCAmelCase : Union[PIL.Image.Image, List[PIL.Image.Image]] , _lowerCAmelCase : int = 1 , _lowerCAmelCase : int = 25 , _lowerCAmelCase : Optional[Union[torch.Generator, List[torch.Generator]]] = None , _lowerCAmelCase : Optional[torch.FloatTensor] = None , _lowerCAmelCase : float = 4.0 , _lowerCAmelCase : int = 64 , _lowerCAmelCase : Optional[str] = "pil" , _lowerCAmelCase : bool = True , ): if isinstance(_lowerCAmelCase , PIL.Image.Image ): A = 1 elif isinstance(_lowerCAmelCase , torch.Tensor ): A = image.shape[0] elif isinstance(_lowerCAmelCase , _lowerCAmelCase ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): A = len(_lowerCAmelCase ) else: raise ValueError( F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_lowerCAmelCase )}""" ) A = self._execution_device A = batch_size * num_images_per_prompt A = guidance_scale > 1.0 A = self._encode_image(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # prior self.scheduler.set_timesteps(_lowerCAmelCase , device=_lowerCAmelCase ) A = self.scheduler.timesteps A = self.prior.config.num_embeddings A = self.prior.config.embedding_dim A = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim A = latents.reshape(latents.shape[0] , _lowerCAmelCase , _lowerCAmelCase ) for i, t in enumerate(self.progress_bar(_lowerCAmelCase ) ): # expand the latents if we are doing classifier free guidance A = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents A = self.scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) A = self.prior( _lowerCAmelCase , timestep=_lowerCAmelCase , proj_embedding=_lowerCAmelCase , ).predicted_image_embedding # remove the variance A , A = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: A , A = noise_pred.chunk(2 ) A = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) A = self.scheduler.step( _lowerCAmelCase , timestep=_lowerCAmelCase , sample=_lowerCAmelCase , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_lowerCAmelCase ) A = [] for i, latent in enumerate(_lowerCAmelCase ): print() A = self.renderer.decode( latent[None, :] , _lowerCAmelCase , size=_lowerCAmelCase , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_lowerCAmelCase ) A = torch.stack(_lowerCAmelCase ) if output_type not in ["np", "pil"]: raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""" ) A = images.cpu().numpy() if output_type == "pil": A = [self.numpy_to_pil(_lowerCAmelCase ) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_lowerCAmelCase )
258
0
'''simple docstring''' import collections import importlib.util import os import re from pathlib import Path a__ : Optional[Any] = 'src/transformers' # Matches is_xxx_available() a__ : Optional[int] = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} a__ : Optional[Any] = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] a__ : Tuple = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available a__ : Optional[int] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") a__ : str = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] a__ : List[str] = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", a__ : Optional[int] = re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], a__ : List[Any] = re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo a__ : Any = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: a__ : Optional[int] = re.compile(R'^\s*try:') # Catches a line with else: a__ : Union[str, Any] = re.compile(R'^\s*else:') def _UpperCamelCase ( __A ) -> Optional[Any]: '''simple docstring''' if _re_test_backend.search(__A ) is None: return None UpperCamelCase__ = [b[0] for b in _re_backend.findall(__A )] backends.sort() return "_and_".join(__A ) def _UpperCamelCase ( __A ) -> str: '''simple docstring''' with open(__A , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCamelCase__ = f.readlines() UpperCamelCase__ = 0 while line_index < len(__A ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(__A ): return None # First grab the objects without a specific backend in _import_structure UpperCamelCase__ = [] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: UpperCamelCase__ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(__A ): UpperCamelCase__ = _re_one_line_import_struct.search(__A ).groups()[0] UpperCamelCase__ = re.findall("\[([^\]]+)\]" , __A ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue UpperCamelCase__ = _re_import_struct_key_value.search(__A ) if single_line_import_search is not None: UpperCamelCase__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(__A ) > 0] objects.extend(__A ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 UpperCamelCase__ = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. UpperCamelCase__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCamelCase__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): UpperCamelCase__ = lines[line_index] if _re_import_struct_add_one.search(__A ) is not None: objects.append(_re_import_struct_add_one.search(__A ).groups()[0] ) elif _re_import_struct_add_many.search(__A ) is not None: UpperCamelCase__ = _re_import_struct_add_many.search(__A ).groups()[0].split(", " ) UpperCamelCase__ = [obj[1:-1] for obj in imports if len(__A ) > 0] objects.extend(__A ) elif _re_between_brackets.search(__A ) is not None: UpperCamelCase__ = _re_between_brackets.search(__A ).groups()[0].split(", " ) UpperCamelCase__ = [obj[1:-1] for obj in imports if len(__A ) > 0] objects.extend(__A ) elif _re_quote_object.search(__A ) is not None: objects.append(_re_quote_object.search(__A ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 12 + "\"" ): objects.append(line[13:-3] ) line_index += 1 UpperCamelCase__ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend UpperCamelCase__ = [] while ( line_index < len(__A ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_import.search(__A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 UpperCamelCase__ = {"none": objects} # Let's continue with backend-specific objects while line_index < len(__A ): # If the line is an if is_backend_available, we grab all objects associated. UpperCamelCase__ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCamelCase__ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCamelCase__ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): UpperCamelCase__ = lines[line_index] UpperCamelCase__ = _re_import.search(__A ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 12 ): objects.append(line[12:-2] ) line_index += 1 UpperCamelCase__ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def _UpperCamelCase ( __A , __A ) -> str: '''simple docstring''' def find_duplicates(__A ): return [k for k, v in collections.Counter(__A ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] UpperCamelCase__ = [] for key in import_dict_objects.keys(): UpperCamelCase__ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) UpperCamelCase__ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): UpperCamelCase__ = "base imports" if key == "none" else F'''{key} backend''' errors.append(F'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def _UpperCamelCase ( ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ = [] for root, _, files in os.walk(__A ): if "__init__.py" in files: UpperCamelCase__ = os.path.join(__A , "__init__.py" ) UpperCamelCase__ = parse_init(__A ) if objects is not None: UpperCamelCase__ = analyze_results(*__A ) if len(__A ) > 0: UpperCamelCase__ = F'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append("\n".join(__A ) ) if len(__A ) > 0: raise ValueError("\n\n".join(__A ) ) def _UpperCamelCase ( ) -> List[str]: '''simple docstring''' UpperCamelCase__ = [] for path, directories, files in os.walk(__A ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(__A ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(__A ) / folder).glob("*.py" ) ) ) == 0: continue UpperCamelCase__ = str((Path(__A ) / folder).relative_to(__A ) ) UpperCamelCase__ = short_path.replace(os.path.sep , "." ) submodules.append(__A ) for fname in files: if fname == "__init__.py": continue UpperCamelCase__ = str((Path(__A ) / fname).relative_to(__A ) ) UpperCamelCase__ = short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(__A ) return submodules a__ : int = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def _UpperCamelCase ( ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = importlib.util.spec_from_file_location( "transformers" , os.path.join(__A , "__init__.py" ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) UpperCamelCase__ = spec.loader.load_module() UpperCamelCase__ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(__A ) > 0: UpperCamelCase__ = "\n".join(F'''- {module}''' for module in module_not_registered ) raise ValueError( "The following submodules are not properly registered in the main init of Transformers:\n" F'''{list_of_modules}\n''' "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
80
'''simple docstring''' import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort _lowerCamelCase : List[Any] = logging.get_logger(__name__) _lowerCamelCase : Union[str, Any] = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class __UpperCAmelCase : '''simple docstring''' def __init__(self : Union[str, Any] , _lowerCAmelCase : Optional[int]=None , **_lowerCAmelCase : Union[str, Any] ): logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) A = model A = kwargs.get("""model_save_dir""" , _lowerCAmelCase ) A = kwargs.get("""latest_model_name""" , _lowerCAmelCase ) def __call__(self : Tuple , **_lowerCAmelCase : Optional[Any] ): A = {k: np.array(_lowerCAmelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCAmelCase , _lowerCAmelCase ) @staticmethod def A (_lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Any]=None , _lowerCAmelCase : Optional[Any]=None ): if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) A = """CPUExecutionProvider""" return ort.InferenceSession(_lowerCAmelCase , providers=[provider] , sess_options=_lowerCAmelCase ) def A (self : List[str] , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : List[str] ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME A = self.model_save_dir.joinpath(self.latest_model_name ) A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) A = self.model_save_dir.joinpath(_lowerCAmelCase ) if src_path.exists(): A = Path(_lowerCAmelCase ).joinpath(_lowerCAmelCase ) try: shutil.copyfile(_lowerCAmelCase , _lowerCAmelCase ) except shutil.SameFileError: pass def A (self : Tuple , _lowerCAmelCase : Union[str, os.PathLike] , **_lowerCAmelCase : str , ): if os.path.isfile(_lowerCAmelCase ): logger.error(F"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(_lowerCAmelCase , exist_ok=_lowerCAmelCase ) # saving model weights/files self._save_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : Optional[Union[bool, str, None]] = None , _lowerCAmelCase : Optional[Union[str, None]] = None , _lowerCAmelCase : bool = False , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional["ort.SessionOptions"] = None , **_lowerCAmelCase : Optional[int] , ): A = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCAmelCase ): A = OnnxRuntimeModel.load_model( os.path.join(_lowerCAmelCase , _lowerCAmelCase ) , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) A = Path(_lowerCAmelCase ) # load model from hub else: # download model A = hf_hub_download( repo_id=_lowerCAmelCase , filename=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , ) A = Path(_lowerCAmelCase ).parent A = Path(_lowerCAmelCase ).name A = OnnxRuntimeModel.load_model(_lowerCAmelCase , provider=_lowerCAmelCase , sess_options=_lowerCAmelCase ) return cls(model=_lowerCAmelCase , **_lowerCAmelCase ) @classmethod def A (cls : str , _lowerCAmelCase : Union[str, Path] , _lowerCAmelCase : bool = True , _lowerCAmelCase : Optional[str] = None , _lowerCAmelCase : Optional[str] = None , **_lowerCAmelCase : str , ): A = None if len(str(_lowerCAmelCase ).split("""@""" ) ) == 2: A , A = model_id.split("""@""" ) return cls._from_pretrained( model_id=_lowerCAmelCase , revision=_lowerCAmelCase , cache_dir=_lowerCAmelCase , force_download=_lowerCAmelCase , use_auth_token=_lowerCAmelCase , **_lowerCAmelCase , )
258
0
from __future__ import annotations import unittest import numpy as np from transformers import LayoutLMConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.layoutlm.modeling_tf_layoutlm import ( TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFLayoutLMForMaskedLM, TFLayoutLMForQuestionAnswering, TFLayoutLMForSequenceClassification, TFLayoutLMForTokenClassification, TFLayoutLMModel, ) class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , 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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=1000 , ) -> Union[str, Any]: UpperCamelCase :Tuple = parent UpperCamelCase :str = batch_size UpperCamelCase :Union[str, Any] = seq_length UpperCamelCase :Tuple = is_training UpperCamelCase :Union[str, Any] = use_input_mask UpperCamelCase :Optional[Any] = use_token_type_ids UpperCamelCase :str = use_labels UpperCamelCase :List[Any] = vocab_size UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :str = num_attention_heads UpperCamelCase :List[str] = intermediate_size UpperCamelCase :Dict = hidden_act UpperCamelCase :str = hidden_dropout_prob UpperCamelCase :Union[str, Any] = attention_probs_dropout_prob UpperCamelCase :List[str] = max_position_embeddings UpperCamelCase :int = type_vocab_size UpperCamelCase :Optional[Any] = type_sequence_label_size UpperCamelCase :Optional[int] = initializer_range UpperCamelCase :Tuple = num_labels UpperCamelCase :List[Any] = num_choices UpperCamelCase :str = scope UpperCamelCase :Tuple = range_bbox def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # convert bbox to numpy since TF does not support item assignment UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ).numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCamelCase :Any = bbox[i, j, 3] UpperCamelCase :Union[str, Any] = bbox[i, j, 1] UpperCamelCase :List[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCamelCase :List[Any] = bbox[i, j, 2] UpperCamelCase :Optional[int] = bbox[i, j, 0] UpperCamelCase :Union[str, Any] = t UpperCamelCase :Optional[Any] = tf.convert_to_tensor(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = None if self.use_input_mask: UpperCamelCase :Any = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Tuple = None if self.use_token_type_ids: UpperCamelCase :str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Optional[Any] = None UpperCamelCase :str = None UpperCamelCase :Union[str, Any] = None if self.use_labels: UpperCamelCase :Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Dict = LayoutLMConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCamelCase :List[str] = TFLayoutLMModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCamelCase :List[str] = TFLayoutLMForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase :Optional[int] = self.num_labels UpperCamelCase :str = TFLayoutLMForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :Union[str, Any] = self.num_labels UpperCamelCase :str = TFLayoutLMForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[Any]: UpperCamelCase :int = TFLayoutLMForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :List[Any] = config_and_inputs UpperCamelCase :Any = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_tf class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Any =( ( TFLayoutLMModel, TFLayoutLMForMaskedLM, TFLayoutLMForTokenClassification, TFLayoutLMForSequenceClassification, TFLayoutLMForQuestionAnswering, ) if is_tf_available() else () ) UpperCamelCase_ : Union[str, Any] =( { 'feature-extraction': TFLayoutLMModel, 'fill-mask': TFLayoutLMForMaskedLM, 'text-classification': TFLayoutLMForSequenceClassification, 'token-classification': TFLayoutLMForTokenClassification, 'zero-shot': TFLayoutLMForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase_ : List[str] =False UpperCamelCase_ : Union[str, Any] =True UpperCamelCase_ : Any =10 def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :List[str] = TFLayoutLMModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Any: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> str: UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Any: for model_name in TF_LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase :str = TFLayoutLMModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip('''Onnx compliancy broke with TF 2.10''' ) def UpperCAmelCase ( self ) -> Tuple: pass def _A ( ): # Here we prepare a batch of 2 sequences to test a LayoutLM forward pass on: # fmt: off UpperCamelCase :str = tf.convert_to_tensor([[101,1019,1014,1016,1037,12849,4747,1004,14246,2278,5439,4524,5002,2930,2193,2930,4341,3208,1005,1055,2171,2848,11300,3531,102],[101,4070,4034,7020,1024,3058,1015,1013,2861,1013,6070,19274,2772,6205,27814,16147,16147,4343,2047,10283,10969,14389,1012,2338,102]] ) # noqa: E231 UpperCamelCase :Dict = tf.convert_to_tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],] ) # noqa: E231 UpperCamelCase :Dict = tf.convert_to_tensor([[[0,0,0,0],[423,237,440,251],[427,272,441,287],[419,115,437,129],[961,885,992,912],[256,38,330,58],[256,38,330,58],[336,42,353,57],[360,39,401,56],[360,39,401,56],[411,39,471,59],[479,41,528,59],[533,39,630,60],[67,113,134,131],[141,115,209,132],[68,149,133,166],[141,149,187,164],[195,148,287,165],[195,148,287,165],[195,148,287,165],[295,148,349,165],[441,149,492,166],[497,149,546,164],[64,201,125,218],[1000,1000,1000,1000]],[[0,0,0,0],[662,150,754,166],[665,199,742,211],[519,213,554,228],[519,213,554,228],[134,433,187,454],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[130,467,204,480],[314,469,376,482],[504,684,582,706],[941,825,973,900],[941,825,973,900],[941,825,973,900],[941,825,973,900],[610,749,652,765],[130,659,168,672],[176,657,237,672],[238,657,312,672],[443,653,628,672],[443,653,628,672],[716,301,825,317],[1000,1000,1000,1000]]] ) # noqa: E231 UpperCamelCase :int = tf.convert_to_tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]] ) # noqa: E231 # these are sequence labels (i.e. at the token level) UpperCamelCase :Dict = tf.convert_to_tensor([[-100,10,10,10,9,1,-100,7,7,-100,7,7,4,2,5,2,8,8,-100,-100,5,0,3,2,-100],[-100,12,12,12,-100,12,10,-100,-100,-100,-100,10,12,9,-100,-100,-100,10,10,10,9,12,-100,10,-100]] ) # noqa: E231 # fmt: on return input_ids, attention_mask, bbox, token_type_ids, labels @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self ) -> Any: UpperCamelCase :List[Any] = TFLayoutLMModel.from_pretrained('''microsoft/layoutlm-base-uncased''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase :List[str] = model(input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) # test the sequence output on [0, :3, :3] UpperCamelCase :List[str] = tf.convert_to_tensor( [[0.1785, -0.1947, -0.0425], [-0.3254, -0.2807, 0.2553], [-0.5391, -0.3322, 0.3364]] , ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) # test the pooled output on [1, :3] UpperCamelCase :Any = tf.convert_to_tensor([-0.6580, -0.0214, 0.8552] ) self.assertTrue(np.allclose(outputs.pooler_output[1, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-3 ) ) @slow def UpperCAmelCase ( self ) -> Optional[int]: # initialize model with randomly initialized sequence classification head UpperCamelCase :str = TFLayoutLMForSequenceClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=2 ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase :str = model( input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=tf.convert_to_tensor([1, 1] ) , ) # test whether we get a loss as a scalar UpperCamelCase :Optional[int] = outputs.loss UpperCamelCase :Optional[int] = (2,) self.assertEqual(loss.shape , SCREAMING_SNAKE_CASE_ ) # test the shape of the logits UpperCamelCase :int = outputs.logits UpperCamelCase :int = (2, 2) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> List[Any]: # initialize model with randomly initialized token classification head UpperCamelCase :List[Any] = TFLayoutLMForTokenClassification.from_pretrained('''microsoft/layoutlm-base-uncased''' , num_labels=13 ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :str = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase :List[Any] = model( input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) # test the shape of the logits UpperCamelCase :Union[str, Any] = outputs.logits UpperCamelCase :List[Any] = tf.convert_to_tensor((2, 25, 13) ) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Dict: # initialize model with randomly initialized token classification head UpperCamelCase :Any = TFLayoutLMForQuestionAnswering.from_pretrained('''microsoft/layoutlm-base-uncased''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = prepare_layoutlm_batch_inputs() # forward pass UpperCamelCase :str = model(input_ids=SCREAMING_SNAKE_CASE_ , bbox=SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) # test the shape of the logits UpperCamelCase :int = tf.convert_to_tensor((2, 25) ) self.assertEqual(outputs.start_logits.shape , SCREAMING_SNAKE_CASE_ ) self.assertEqual(outputs.end_logits.shape , SCREAMING_SNAKE_CASE_ )
259
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : List[Any] =['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = size if size is not None else {'''height''': 224, '''width''': 224} UpperCamelCase :Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) UpperCamelCase :Optional[int] = do_resize UpperCamelCase :int = do_rescale UpperCamelCase :Tuple = do_normalize UpperCamelCase :str = do_center_crop UpperCamelCase :int = crop_size UpperCamelCase :Tuple = size UpperCamelCase :List[str] = resample UpperCamelCase :Tuple = rescale_factor UpperCamelCase :Optional[Any] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN UpperCamelCase :Optional[int] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "shortest_edge" in size: UpperCamelCase :str = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size['''shortest_edge'''] , default_to_square=SCREAMING_SNAKE_CASE_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: UpperCamelCase :Optional[int] = (size['''height'''], size['''width''']) else: raise ValueError(F'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}''' ) 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: UpperCamelCase :Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ ) -> np.ndarray: 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_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **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_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ) -> BatchFeature: UpperCamelCase :Union[str, Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase :Optional[int] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase :Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase :Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase :Optional[int] = crop_size if crop_size is not None else self.crop_size UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = resample if resample is not None else self.resample UpperCamelCase :List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase :Optional[Any] = image_mean if image_mean is not None else self.image_mean UpperCamelCase :Dict = image_std if image_std is not None else self.image_std UpperCamelCase :Dict = size if size is not None else self.size UpperCamelCase :Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE_ ) if not is_batched(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = [images] if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. UpperCamelCase :Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase :List[Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: UpperCamelCase :Tuple = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase :Union[str, Any] = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase :Union[str, Any] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :List[str] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :int = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
259
1
import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __snake_case = logging.get_logger(__name__) __snake_case = { """facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""", # See all DETR models at https://huggingface.co/models?filter=detr } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Tuple ='detr' UpperCamelCase_ : Optional[int] =['past_key_values'] UpperCamelCase_ : Optional[Any] ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=100 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=2048 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=2048 , SCREAMING_SNAKE_CASE_=8 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="relu" , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1.0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="sine" , SCREAMING_SNAKE_CASE_="resnet50" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.1 , **SCREAMING_SNAKE_CASE_ , ) -> List[str]: if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) UpperCamelCase :List[str] = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = backbone_config.get('''model_type''' ) UpperCamelCase :List[str] = CONFIG_MAPPING[backbone_model_type] UpperCamelCase :int = config_class.from_dict(SCREAMING_SNAKE_CASE_ ) # set timm attributes to None UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = None, None, None UpperCamelCase :int = use_timm_backbone UpperCamelCase :Tuple = backbone_config UpperCamelCase :Dict = num_channels UpperCamelCase :Tuple = num_queries UpperCamelCase :str = d_model UpperCamelCase :Union[str, Any] = encoder_ffn_dim UpperCamelCase :Optional[int] = encoder_layers UpperCamelCase :Tuple = encoder_attention_heads UpperCamelCase :List[Any] = decoder_ffn_dim UpperCamelCase :Optional[Any] = decoder_layers UpperCamelCase :Optional[int] = decoder_attention_heads UpperCamelCase :Union[str, Any] = dropout UpperCamelCase :List[Any] = attention_dropout UpperCamelCase :Union[str, Any] = activation_dropout UpperCamelCase :Tuple = activation_function UpperCamelCase :Optional[Any] = init_std UpperCamelCase :int = init_xavier_std UpperCamelCase :List[Any] = encoder_layerdrop UpperCamelCase :List[str] = decoder_layerdrop UpperCamelCase :Optional[Any] = encoder_layers UpperCamelCase :Optional[Any] = auxiliary_loss UpperCamelCase :List[Any] = position_embedding_type UpperCamelCase :Tuple = backbone UpperCamelCase :str = use_pretrained_backbone UpperCamelCase :str = dilation # Hungarian matcher UpperCamelCase :Any = class_cost UpperCamelCase :str = bbox_cost UpperCamelCase :List[str] = giou_cost # Loss coefficients UpperCamelCase :Tuple = mask_loss_coefficient UpperCamelCase :Tuple = dice_loss_coefficient UpperCamelCase :Union[str, Any] = bbox_loss_coefficient UpperCamelCase :List[str] = giou_loss_coefficient UpperCamelCase :Tuple = eos_coefficient super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase ( self ) -> int: return self.encoder_attention_heads @property def UpperCAmelCase ( self ) -> int: return self.d_model @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Any: return cls(backbone_config=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict[str, any]: UpperCamelCase :Union[str, Any] = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: UpperCamelCase :int = self.backbone_config.to_dict() UpperCamelCase :Any = self.__class__.model_type return output class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Any =version.parse('1.11' ) @property def UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def UpperCAmelCase ( self ) -> float: return 1e-5 @property def UpperCAmelCase ( self ) -> int: return 12
259
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str]=() , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]="no" , SCREAMING_SNAKE_CASE__ : Dict="29500" ): UpperCamelCase :List[Any] = False UpperCamelCase :Tuple = False if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ): UpperCamelCase :Dict = True elif "IPython" in sys.modules: UpperCamelCase :int = '''google.colab''' in str(sys.modules['''IPython'''].get_ipython() ) try: UpperCamelCase :Any = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.''' ) if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME''' , SCREAMING_SNAKE_CASE__ ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside ''' '''your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if num_processes is None: UpperCamelCase :Tuple = 8 UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''TPU''' ) print(F'''Launching a training on {num_processes} TPU cores.''' ) xmp.spawn(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on one CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) else: if num_processes is None: raise ValueError( '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized ''' '''inside your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if torch.cuda.is_initialized(): raise ValueError( '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction ''' '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA ''' '''function.''' ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port=SCREAMING_SNAKE_CASE__ , mixed_precision=SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''MULTI_GPU''' ) print(F'''Launching training on {num_processes} GPUs.''' ) try: start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. ''' '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. ''' '''Please review your imports and test them when running the `notebook_launcher()` to identify ''' '''which one is problematic.''' ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): UpperCamelCase :Any = '''1''' print('''Launching training on MPS.''' ) elif torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple=() , SCREAMING_SNAKE_CASE__ : int=2 ): from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port='''29500''' , accelerate_mixed_precision='''no''' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='''yes''' , ): UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , debug=SCREAMING_SNAKE_CASE__ ) start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' )
259
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """uw-madison/mra-base-512-4""": """https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : int ='mra' def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , 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_=1 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="full" , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ) -> Dict: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = vocab_size UpperCamelCase :str = max_position_embeddings UpperCamelCase :Dict = hidden_size UpperCamelCase :Any = num_hidden_layers UpperCamelCase :List[str] = num_attention_heads UpperCamelCase :Any = intermediate_size UpperCamelCase :Any = hidden_act UpperCamelCase :Any = hidden_dropout_prob UpperCamelCase :Optional[Any] = attention_probs_dropout_prob UpperCamelCase :List[str] = initializer_range UpperCamelCase :Optional[Any] = type_vocab_size UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Optional[Any] = position_embedding_type UpperCamelCase :Any = block_per_row UpperCamelCase :List[Any] = approx_mode UpperCamelCase :Tuple = initial_prior_first_n_blocks UpperCamelCase :Union[str, Any] = initial_prior_diagonal_n_blocks
259
import sys def _A ( SCREAMING_SNAKE_CASE__ : List[str] ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] UpperCamelCase :List[Any] = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] for chain_length in range(2 , SCREAMING_SNAKE_CASE__ ): for a in range(1 , n - chain_length + 1 ): UpperCamelCase :Optional[Any] = a + chain_length - 1 UpperCamelCase :int = sys.maxsize for c in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Any = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: UpperCamelCase :int = cost UpperCamelCase :List[str] = c return matrix, sol def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ): if i == j: print('''A''' + str(SCREAMING_SNAKE_CASE__ ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] + 1 , SCREAMING_SNAKE_CASE__ ) print(''')''' , end=''' ''' ) def _A ( ): UpperCamelCase :Optional[int] = [30, 35, 15, 5, 10, 20, 25] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 UpperCamelCase , UpperCamelCase :Dict = matrix_chain_order(SCREAMING_SNAKE_CASE__ ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , 1 , n - 1 ) if __name__ == "__main__": main()
259
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin __snake_case = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=14 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=[1, 2, 3, 4, 5] , SCREAMING_SNAKE_CASE_=25 , SCREAMING_SNAKE_CASE_=5 , ) -> str: UpperCamelCase :Any = d_model UpperCamelCase :List[str] = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :str = prediction_length UpperCamelCase :str = context_length UpperCamelCase :int = cardinality UpperCamelCase :Optional[Any] = num_time_features UpperCamelCase :Optional[Any] = lags_sequence UpperCamelCase :str = embedding_dimension UpperCamelCase :str = is_training UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :int = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :Optional[int] = context_length UpperCamelCase :Tuple = prediction_length + label_length UpperCamelCase :Optional[Any] = label_length UpperCamelCase :Optional[int] = moving_average UpperCamelCase :Union[str, Any] = autocorrelation_factor def UpperCAmelCase ( self ) -> Optional[int]: return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :Optional[Any] = config.context_length + max(config.lags_sequence ) UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) UpperCamelCase :List[str] = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) UpperCamelCase :Union[str, Any] = floats_tensor([self.batch_size, _past_length] ) UpperCamelCase :Any = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs UpperCamelCase :Tuple = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) UpperCamelCase :int = floats_tensor([self.batch_size, config.prediction_length] ) UpperCamelCase :Union[str, Any] = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :int = self.get_config() UpperCamelCase :Union[str, Any] = self.prepare_autoformer_inputs_dict(SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def UpperCAmelCase ( self ) -> Any: UpperCamelCase , UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCamelCase :int = AutoformerModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase :Any = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = outputs.encoder_last_hidden_state UpperCamelCase :str = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Any = model.get_encoder() encoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = AutoformerEncoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = model.create_network_inputs(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) UpperCamelCase :Tuple = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) UpperCamelCase :Optional[Any] = encoder(inputs_embeds=SCREAMING_SNAKE_CASE_ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) UpperCamelCase :Optional[Any] = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) UpperCamelCase :Union[str, Any] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) UpperCamelCase :Tuple = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) UpperCamelCase :Optional[Any] = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Union[str, Any] = model.get_decoder() decoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoformerDecoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = decoder( trend=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[str] =(AutoformerModel, AutoformerForPrediction) if is_torch_available() else () UpperCamelCase_ : List[str] =(AutoformerForPrediction,) if is_torch_available() else () UpperCamelCase_ : Optional[Any] ={'feature-extraction': AutoformerModel} if is_torch_available() else {} UpperCamelCase_ : Any =False UpperCamelCase_ : List[str] =False UpperCamelCase_ : Dict =False UpperCamelCase_ : Dict =False UpperCamelCase_ : int =False UpperCamelCase_ : Optional[int] =False def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = AutoformerModelTester(self ) UpperCamelCase :int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase , UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: UpperCamelCase :Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :List[str] = model_class.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertEqual(info['''missing_keys'''] , [] ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = inspect.signature(getattr(SCREAMING_SNAKE_CASE_ , '''forward''' ) ) # The main input is the name of the argument after `self` UpperCamelCase :List[str] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Tuple = [*signature.parameters.keys()] UpperCamelCase :Optional[Any] = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(SCREAMING_SNAKE_CASE_ )] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = True UpperCamelCase :Dict = getattr(self.model_tester , '''seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = getattr(self.model_tester , '''decoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = getattr(self.model_tester , '''encoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = getattr(self.model_tester , '''d_model''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = getattr(self.model_tester , '''num_attention_heads''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = d_model // num_attention_heads for model_class in self.all_model_classes: UpperCamelCase :Tuple = True UpperCamelCase :Tuple = False UpperCamelCase :Any = True UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :int = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # decoder attentions UpperCamelCase :Union[str, Any] = outputs.decoder_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions UpperCamelCase :Union[str, Any] = outputs.cross_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine UpperCamelCase :Any = True UpperCamelCase :int = True UpperCamelCase :Any = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(out_len + 2 , len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def UpperCAmelCase ( self ) -> List[Any]: super().test_retain_grad_hidden_states_attentions() def _A ( SCREAMING_SNAKE_CASE__ : int="train-batch.pt" ): UpperCamelCase :Union[str, Any] = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) UpperCamelCase :Tuple = torch.load(SCREAMING_SNAKE_CASE__ , map_location=SCREAMING_SNAKE_CASE__ ) return batch @require_torch @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :int = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = prepare_batch() with torch.no_grad(): UpperCamelCase :Optional[Any] = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] UpperCamelCase :Union[str, Any] = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Dict = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state UpperCamelCase :Union[str, Any] = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Tuple = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) UpperCamelCase :Optional[int] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , SCREAMING_SNAKE_CASE_ , rtol=1e-1 ) )
259
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() __snake_case = logging.get_logger(__name__) __snake_case = """https://openaipublic.azureedge.net/jukebox/models/""" __snake_case = { """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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] ): if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :int = key.replace('''.model.1.bias''' , '''.conv1d_1.bias''' ) elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Union[str, Any] = key.replace('''.model.1.weight''' , '''.conv1d_1.weight''' ) elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[Any] = key.replace('''.model.3.bias''' , '''.conv1d_2.bias''' ) elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[int] = key.replace('''.model.3.weight''' , '''.conv1d_2.weight''' ) if "conditioner_blocks.0." in key: UpperCamelCase :Any = key.replace('''conditioner_blocks.0''' , '''conditioner_blocks''' ) if "prime_prior" in key: UpperCamelCase :int = 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 :Any = 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 :str = 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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Optional[int] = {} import re UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :str = re.compile( R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[int] = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[Any] = re.compile(R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = 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(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_encoder_block_conv_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :List[Any] = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_encoder_block_conv_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_encoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = regex_match.groups() UpperCamelCase :Any = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :Any = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :str = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' UpperCamelCase :List[str] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = prefix + resnet_block UpperCamelCase :str = re_encoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_proj_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_encoder_block_proj_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = regex_match.groups() UpperCamelCase :int = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' UpperCamelCase :str = re_encoder_block_proj_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = re_decoder_block_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :Optional[int] = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Any = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' UpperCamelCase :Optional[int] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Optional[int] = re_decoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_decoder_block_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = regex_match.groups() UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_decoder_block_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_prior_cond_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_prior_cond_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_prior_cond_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :Optional[Any] = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :int = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' UpperCamelCase :List[Any] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Dict = re_prior_cond_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[str] = re_prior_cond_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :Dict = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_prior_cond_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # keep original key else: UpperCamelCase :List[str] = original_key UpperCamelCase :Any = replace_key(SCREAMING_SNAKE_CASE__ ) 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 :Union[str, Any] = model_state_dict[F'''{key_prefix}.{key}'''] print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) UpperCamelCase :List[Any] = original_key UpperCamelCase :Any = original_key UpperCamelCase :Optional[int] = value return new_dict @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Dict=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): UpperCamelCase :Dict = requests.get(F'''{PREFIX}{file}''' , allow_redirects=SCREAMING_SNAKE_CASE__ ) os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=SCREAMING_SNAKE_CASE__ ) open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , '''wb''' ).write(r.content ) UpperCamelCase :Optional[int] = MODEL_MAPPING[model_name.split('''/''' )[-1]] UpperCamelCase :Any = JukeboxConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = JukeboxModel(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [] UpperCamelCase :List[Any] = {} for i, dict_name in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )['''model'''] UpperCamelCase :Tuple = {} for k in old_dic.keys(): if k.endswith('''.b''' ): UpperCamelCase :Optional[int] = old_dic[k] elif k.endswith('''.w''' ): UpperCamelCase :Optional[Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: UpperCamelCase :Optional[Any] = old_dic[k] else: UpperCamelCase :Any = old_dic[k] UpperCamelCase :Any = '''vqvae''' if i == 0 else F'''priors.{3 - i}''' UpperCamelCase :Dict = fix_jukebox_keys(SCREAMING_SNAKE_CASE__ , model.state_dict() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) weight_dict.append(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = weight_dict.pop(0 ) model.vqvae.load_state_dict(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) with open(F'''{pytorch_dump_folder_path}/mapping.json''' , '''w''' ) as txtfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) return weight_dict if __name__ == "__main__": __snake_case = 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.""", ) __snake_case = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
259
1
import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :str = 0 @slow def UpperCAmelCase ( self ) -> List[str]: for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): UpperCamelCase :Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE_ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): UpperCamelCase :int = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(SCREAMING_SNAKE_CASE_ ) , 0 ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Any = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 20 ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Dict = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Check that tokenizer_type ≠ model_type UpperCamelCase :int = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , config=SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 12 ) def UpperCAmelCase ( self ) -> Any: with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) ) UpperCamelCase :Optional[int] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , tokenizer_type='''bert''' , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''merges.txt''' ) ) UpperCamelCase :Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , tokenizer_type='''gpt2''' , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @require_tokenizers def UpperCAmelCase ( self ) -> str: with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.txt''' ) ) UpperCamelCase :Union[str, Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , tokenizer_type='''bert''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(SCREAMING_SNAKE_CASE_ , '''merges.txt''' ) ) UpperCamelCase :Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , tokenizer_type='''gpt2''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE_ ): AutoTokenizer.from_pretrained('''./''' , tokenizer_type='''xxx''' ) @require_tokenizers def UpperCAmelCase ( self ) -> int: for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: UpperCamelCase :Dict = tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (BertTokenizer, BertTokenizerFast) ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , SCREAMING_SNAKE_CASE_ ) else: self.assertEqual(tokenizer.do_lower_case , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.model_max_length , 512 ) @require_tokenizers def UpperCAmelCase ( self ) -> Union[str, Any]: for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier''' , ): UpperCamelCase :Optional[Any] = tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' ) def UpperCAmelCase ( self ) -> Dict: # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai UpperCamelCase :Optional[int] = TOKENIZER_MAPPING.values() UpperCamelCase :List[Any] = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(SCREAMING_SNAKE_CASE_ ) @require_tokenizers def UpperCAmelCase ( self ) -> Optional[Any]: self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' ) , SCREAMING_SNAKE_CASE_ ) @require_tokenizers def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :str = AutoTokenizer.from_pretrained('''distilbert-base-uncased''' , do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = '''Hello, world. How are you?''' UpperCamelCase :Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertEqual('''[UNK]''' , tokens[0] ) UpperCamelCase :str = AutoTokenizer.from_pretrained('''microsoft/mpnet-base''' , do_lower_case=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = tokenizer.tokenize(SCREAMING_SNAKE_CASE_ ) self.assertEqual('''[UNK]''' , tokens[0] ) @require_tokenizers def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' ) self.assertEqual(type(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.model_max_length , 512 ) self.assertEqual(tokenizer.vocab_size , 3_0000 ) self.assertEqual(tokenizer.unk_token , '''[UNK]''' ) self.assertEqual(tokenizer.padding_side , '''right''' ) self.assertEqual(tokenizer.truncation_side , '''right''' ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :List[str] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 12 ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Dict = AutoTokenizer.from_pretrained('''ctrl''' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: # Check we can load the tokenizer config of an online model. UpperCamelCase :str = get_tokenizer_config('''bert-base-cased''' ) UpperCamelCase :Optional[Any] = config.pop('''_commit_hash''' , SCREAMING_SNAKE_CASE_ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(SCREAMING_SNAKE_CASE_ , {'''do_lower_case''': False} ) # This model does not have a tokenizer_config so we get back an empty dict. UpperCamelCase :Tuple = get_tokenizer_config(SCREAMING_SNAKE_CASE_ ) self.assertDictEqual(SCREAMING_SNAKE_CASE_ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. UpperCamelCase :int = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = get_tokenizer_config(SCREAMING_SNAKE_CASE_ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['''tokenizer_class'''] , '''BertTokenizer''' ) def UpperCAmelCase ( self ) -> Dict: try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE_ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , slow_tokenizer_class=SCREAMING_SNAKE_CASE_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE_ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , slow_tokenizer_class=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = CustomTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def UpperCAmelCase ( self ) -> Optional[Any]: try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE_ ) # Can register in two steps AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , slow_tokenizer_class=SCREAMING_SNAKE_CASE_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , fast_tokenizer_class=SCREAMING_SNAKE_CASE_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( SCREAMING_SNAKE_CASE_ , slow_tokenizer_class=SCREAMING_SNAKE_CASE_ , fast_tokenizer_class=SCREAMING_SNAKE_CASE_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(SCREAMING_SNAKE_CASE_ ): AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , fast_tokenizer_class=SCREAMING_SNAKE_CASE_ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase :Union[str, Any] = BertTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) bert_tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = CustomTokenizerFast.from_pretrained(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase ( self ) -> int: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :List[Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , trust_remote_code=SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) @require_tokenizers def UpperCAmelCase ( self ) -> int: class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Union[str, Any] =False class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =NewTokenizer UpperCamelCase_ : Optional[Any] =False try: AutoConfig.register('''custom''' , SCREAMING_SNAKE_CASE_ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , slow_tokenizer_class=SCREAMING_SNAKE_CASE_ ) AutoTokenizer.register(SCREAMING_SNAKE_CASE_ , fast_tokenizer_class=SCREAMING_SNAKE_CASE_ ) # If remote code is not set, the default is to use local UpperCamelCase :str = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) UpperCamelCase :int = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. UpperCamelCase :str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) UpperCamelCase :List[str] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub UpperCamelCase :Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertTrue(tokenizer.special_attribute_present ) UpperCamelCase :Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :List[str] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE_ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version UpperCamelCase :Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=SCREAMING_SNAKE_CASE_ , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def UpperCAmelCase ( self ) -> Tuple: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , '''bert-base is not a local folder and is not a valid model identifier''' ): UpperCamelCase :Union[str, Any] = AutoTokenizer.from_pretrained('''bert-base''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: with self.assertRaisesRegex( SCREAMING_SNAKE_CASE_ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE_ , revision='''aaaaaa''' ) def UpperCAmelCase ( self ) -> str: # Make sure we have cached the tokenizer. UpperCamelCase :Union[str, Any] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: UpperCamelCase :List[Any] = AutoTokenizer.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 )
259
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Union[str, Any] =ViTImageProcessor if is_vision_available() else None @property def UpperCAmelCase ( self ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = (3, 32, 128) UpperCamelCase :Any = tempfile.mkdtemp() # fmt: off UpperCamelCase :int = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on UpperCamelCase :Optional[int] = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase :Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) UpperCamelCase :Tuple = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } UpperCamelCase :str = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> int: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) UpperCamelCase :List[Any] = Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) return image_input def UpperCAmelCase ( self ) -> str: UpperCamelCase :str = self.get_tokenizer() UpperCamelCase :Union[str, Any] = self.get_image_processor() UpperCamelCase :List[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Dict = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[int] = self.get_tokenizer() UpperCamelCase :Dict = self.get_image_processor() UpperCamelCase :List[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) UpperCamelCase :Optional[Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) UpperCamelCase :int = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_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 ) -> Union[str, Any]: UpperCamelCase :Tuple = self.get_image_processor() UpperCamelCase :List[str] = self.get_tokenizer() UpperCamelCase :str = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = self.prepare_image_inputs() UpperCamelCase :List[str] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) UpperCamelCase :Optional[Any] = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = self.get_image_processor() UpperCamelCase :Union[str, Any] = self.get_tokenizer() UpperCamelCase :int = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = '''test''' UpperCamelCase :Optional[int] = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = tokenizer(SCREAMING_SNAKE_CASE_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.get_image_processor() UpperCamelCase :Tuple = self.get_tokenizer() UpperCamelCase :Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = '''test''' UpperCamelCase :str = self.prepare_image_inputs() UpperCamelCase :Dict = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''labels'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[Any] = self.get_image_processor() UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase :Union[str, Any] = processor.char_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :List[Any] = self.get_image_processor() UpperCamelCase :Optional[Any] = self.get_tokenizer() UpperCamelCase :Any = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = None UpperCamelCase :List[Any] = self.prepare_image_inputs() UpperCamelCase :Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :str = self.get_image_processor() UpperCamelCase :Tuple = self.get_tokenizer() UpperCamelCase :Optional[int] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.randn(1 , 27 , 38 ) UpperCamelCase :Union[str, Any] = torch.randn(1 , 27 , 5_0257 ) UpperCamelCase :Optional[Any] = torch.randn(1 , 27 , 3_0522 ) UpperCamelCase :Optional[Any] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
259
1
import functools from typing import Any def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[str] ): # Validation if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0: raise ValueError('''the string should be not empty string''' ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not all( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) > 0 for item in words ): raise ValueError('''the words should be a list of non-empty strings''' ) # Build trie UpperCamelCase :dict[str, Any] = {} UpperCamelCase :int = '''WORD_KEEPER''' for word in words: UpperCamelCase :str = trie for c in word: if c not in trie_node: UpperCamelCase :Optional[Any] = {} UpperCamelCase :int = trie_node[c] UpperCamelCase :Optional[int] = True UpperCamelCase :Tuple = len(SCREAMING_SNAKE_CASE__ ) # Dynamic programming method @functools.cache def is_breakable(SCREAMING_SNAKE_CASE__ : int ) -> bool: if index == len_string: return True UpperCamelCase :Tuple = trie for i in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[Any] = trie_node.get(string[i] , SCREAMING_SNAKE_CASE__ ) if trie_node is None: return False if trie_node.get(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
259
import math def _A ( SCREAMING_SNAKE_CASE__ : int = 100 ): UpperCamelCase :Dict = sum(i * i for i in range(1 , n + 1 ) ) UpperCamelCase :List[str] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
259
1
import random import torch from huggingface_hub import HfApi from diffusers import UNetaDModel __snake_case = HfApi() __snake_case = {} # fmt: off __snake_case = torch.tensor([ -0.7_5_1_5, -1.6_8_8_3, 0.2_4_2_0, 0.0_3_0_0, 0.6_3_4_7, 1.3_4_3_3, -1.1_7_4_3, -3.7_4_6_7, 1.2_3_4_2, -2.2_4_8_5, 0.4_6_3_6, 0.8_0_7_6, -0.7_9_9_1, 0.3_9_6_9, 0.8_4_9_8, 0.9_1_8_9, -1.8_8_8_7, -3.3_5_2_2, 0.7_6_3_9, 0.2_0_4_0, 0.6_2_7_1, -2.7_1_4_8, -1.6_3_1_6, 3.0_8_3_9, 0.3_1_8_6, 0.2_7_2_1, -0.9_7_5_9, -1.2_4_6_1, 2.6_2_5_7, 1.3_5_5_7 ]) __snake_case = torch.tensor([ -2.3_6_3_9, -2.5_3_4_4, 0.0_0_5_4, -0.6_6_7_4, 1.5_9_9_0, 1.0_1_5_8, 0.3_1_2_4, -2.1_4_3_6, 1.8_7_9_5, -2.5_4_2_9, -0.1_5_6_6, -0.3_9_7_3, 1.2_4_9_0, 2.6_4_4_7, 1.2_2_8_3, -0.5_2_0_8, -2.8_1_5_4, -3.5_1_1_9, 2.3_8_3_8, 1.2_0_3_3, 1.7_2_0_1, -2.1_2_5_6, -1.4_5_7_6, 2.7_9_4_8, 2.4_2_0_4, -0.9_7_5_2, -1.2_5_4_6, 0.8_0_2_7, 3.2_7_5_8, 3.1_3_6_5 ]) __snake_case = torch.tensor([ -0.6_5_3_1, -0.6_8_9_1, -0.3_1_7_2, -0.5_3_7_5, -0.9_1_4_0, -0.5_3_6_7, -0.1_1_7_5, -0.7_8_6_9, -0.3_8_0_8, -0.4_5_1_3, -0.2_0_9_8, -0.0_0_8_3, 0.3_1_8_3, 0.5_1_4_0, 0.2_2_4_7, -0.1_3_0_4, -0.1_3_0_2, -0.2_8_0_2, -0.2_0_8_4, -0.2_0_2_5, -0.4_9_6_7, -0.4_8_7_3, -0.0_8_6_1, 0.6_9_2_5, 0.0_2_5_0, 0.1_2_9_0, -0.1_5_4_3, 0.6_3_1_6, 1.0_4_6_0, 1.4_9_4_3 ]) __snake_case = torch.tensor([ 0.0_9_1_1, 0.1_1_0_7, 0.0_1_8_2, 0.0_4_3_5, -0.0_8_0_5, -0.0_6_0_8, 0.0_3_8_1, 0.2_1_7_2, -0.0_2_8_0, 0.1_3_2_7, -0.0_2_9_9, -0.0_2_5_5, -0.0_0_5_0, -0.1_1_7_0, -0.1_0_4_6, 0.0_3_0_9, 0.1_3_6_7, 0.1_7_2_8, -0.0_5_3_3, -0.0_7_4_8, -0.0_5_3_4, 0.1_6_2_4, 0.0_3_8_4, -0.1_8_0_5, -0.0_7_0_7, 0.0_6_4_2, 0.0_2_2_0, -0.0_1_3_4, -0.1_3_3_3, -0.1_5_0_5 ]) __snake_case = torch.tensor([ 0.1_3_2_1, 0.1_3_3_7, 0.0_4_4_0, 0.0_6_2_2, -0.0_5_9_1, -0.0_3_7_0, 0.0_5_0_3, 0.2_1_3_3, -0.0_1_7_7, 0.1_4_1_5, -0.0_1_1_6, -0.0_1_1_2, 0.0_0_4_4, -0.0_9_8_0, -0.0_7_8_9, 0.0_3_9_5, 0.1_5_0_2, 0.1_7_8_5, -0.0_4_8_8, -0.0_5_1_4, -0.0_4_0_4, 0.1_5_3_9, 0.0_4_5_4, -0.1_5_5_9, -0.0_6_6_5, 0.0_6_5_9, 0.0_3_8_3, -0.0_0_0_5, -0.1_2_6_6, -0.1_3_8_6 ]) __snake_case = torch.tensor([ 0.1_1_5_4, 0.1_2_1_8, 0.0_3_0_7, 0.0_5_2_6, -0.0_7_1_1, -0.0_5_4_1, 0.0_3_6_6, 0.2_0_7_8, -0.0_2_6_7, 0.1_3_1_7, -0.0_2_2_6, -0.0_1_9_3, -0.0_0_1_4, -0.1_0_5_5, -0.0_9_0_2, 0.0_3_3_0, 0.1_3_9_1, 0.1_7_0_9, -0.0_5_6_2, -0.0_6_9_3, -0.0_5_6_0, 0.1_4_8_2, 0.0_3_8_1, -0.1_6_8_3, -0.0_6_8_1, 0.0_6_6_1, 0.0_3_3_1, -0.0_0_4_6, -0.1_2_6_8, -0.1_4_3_1 ]) __snake_case = torch.tensor([ 0.1_1_9_2, 0.1_2_4_0, 0.0_4_1_4, 0.0_6_0_6, -0.0_5_5_7, -0.0_4_1_2, 0.0_4_3_0, 0.2_0_4_2, -0.0_2_0_0, 0.1_3_8_5, -0.0_1_1_5, -0.0_1_3_2, 0.0_0_1_7, -0.0_9_6_5, -0.0_8_0_2, 0.0_3_9_8, 0.1_4_3_3, 0.1_7_4_7, -0.0_4_5_8, -0.0_5_3_3, -0.0_4_0_7, 0.1_5_4_5, 0.0_4_1_9, -0.1_5_7_4, -0.0_6_4_5, 0.0_6_2_6, 0.0_3_4_1, -0.0_0_1_0, -0.1_1_9_9, -0.1_3_9_0 ]) __snake_case = torch.tensor([ 0.1_0_7_5, 0.1_0_7_4, 0.0_2_0_5, 0.0_4_3_1, -0.0_7_7_4, -0.0_6_0_7, 0.0_2_9_8, 0.2_0_4_2, -0.0_3_2_0, 0.1_2_6_7, -0.0_2_8_1, -0.0_2_5_0, -0.0_0_6_4, -0.1_0_9_1, -0.0_9_4_6, 0.0_2_9_0, 0.1_3_2_8, 0.1_6_5_0, -0.0_5_8_0, -0.0_7_3_8, -0.0_5_8_6, 0.1_4_4_0, 0.0_3_3_7, -0.1_7_4_6, -0.0_7_1_2, 0.0_6_0_5, 0.0_2_5_0, -0.0_0_9_9, -0.1_3_1_6, -0.1_4_7_3 ]) __snake_case = torch.tensor([ -1.4_5_7_2, -2.0_4_8_1, -0.0_4_1_4, -0.6_0_0_5, 1.4_1_3_6, 0.5_8_4_8, 0.4_0_2_8, -2.7_3_3_0, 1.2_2_1_2, -2.1_2_2_8, 0.2_1_5_5, 0.4_0_3_9, 0.7_6_6_2, 2.0_5_3_5, 0.7_4_7_7, -0.3_2_4_3, -2.1_7_5_8, -2.7_6_4_8, 1.6_9_4_7, 0.7_0_2_6, 1.2_3_3_8, -1.6_0_7_8, -0.8_6_8_2, 2.2_8_1_0, 1.8_5_7_4, -0.5_7_1_8, -0.5_5_8_6, -0.0_1_8_6, 2.3_4_1_5, 2.1_2_5_1]) __snake_case = torch.tensor([ -1.3_6_9_0, -1.9_7_2_0, -0.4_0_9_0, -0.6_9_6_6, 1.4_6_6_0, 0.9_9_3_8, -0.1_3_8_5, -2.7_3_2_4, 0.7_7_3_6, -1.8_9_1_7, 0.2_9_2_3, 0.4_2_9_3, 0.1_6_9_3, 1.4_1_1_2, 1.1_8_8_7, -0.3_1_8_1, -2.2_1_6_0, -2.6_3_8_1, 1.3_1_7_0, 0.8_1_6_3, 0.9_2_4_0, -1.6_5_4_4, -0.6_0_9_9, 2.5_2_5_9, 1.6_4_3_0, -0.9_0_9_0, -0.9_3_9_2, -0.0_1_2_6, 2.4_2_6_8, 2.3_2_6_6 ]) __snake_case = torch.tensor([ -1.3_5_2_5, -1.9_6_2_8, -0.3_9_5_6, -0.6_8_6_0, 1.4_6_6_4, 1.0_0_1_4, -0.1_2_5_9, -2.7_2_1_2, 0.7_7_7_2, -1.8_8_1_1, 0.2_9_9_6, 0.4_3_8_8, 0.1_7_0_4, 1.4_0_2_9, 1.1_7_0_1, -0.3_0_2_7, -2.2_0_5_3, -2.6_2_8_7, 1.3_3_5_0, 0.8_1_3_1, 0.9_2_7_4, -1.6_2_9_2, -0.6_0_9_8, 2.5_1_3_1, 1.6_5_0_5, -0.8_9_5_8, -0.9_2_9_8, -0.0_1_5_1, 2.4_2_5_7, 2.3_3_5_5 ]) __snake_case = torch.tensor([ -2.0_5_8_5, -2.7_8_9_7, -0.2_8_5_0, -0.8_9_4_0, 1.9_0_5_2, 0.5_7_0_2, 0.6_3_4_5, -3.8_9_5_9, 1.5_9_3_2, -3.2_3_1_9, 0.1_9_7_4, 0.0_2_8_7, 1.7_5_6_6, 2.6_5_4_3, 0.8_3_8_7, -0.5_3_5_1, -3.2_7_3_6, -4.3_3_7_5, 2.9_0_2_9, 1.6_3_9_0, 1.4_6_4_0, -2.1_7_0_1, -1.9_0_1_3, 2.9_3_4_1, 3.4_9_8_1, -0.6_2_5_5, -1.1_6_4_4, -0.1_5_9_1, 3.7_0_9_7, 3.2_0_6_6 ]) __snake_case = torch.tensor([ -2.3_1_3_9, -2.5_5_9_4, -0.0_1_9_7, -0.6_7_8_5, 1.7_0_0_1, 1.1_6_0_6, 0.3_0_7_5, -2.1_7_4_0, 1.8_0_7_1, -2.5_6_3_0, -0.0_9_2_6, -0.3_8_1_1, 1.2_1_1_6, 2.6_2_4_6, 1.2_7_3_1, -0.5_3_9_8, -2.8_1_5_3, -3.6_1_4_0, 2.3_8_9_3, 1.3_2_6_2, 1.6_2_5_8, -2.1_8_5_6, -1.3_2_6_7, 2.8_3_9_5, 2.3_7_7_9, -1.0_6_2_3, -1.2_4_6_8, 0.8_9_5_9, 3.3_3_6_7, 3.2_2_4_3 ]) __snake_case = torch.tensor([ -2.0_6_2_8, -2.7_6_6_7, -0.2_0_8_9, -0.8_2_6_3, 2.0_5_3_9, 0.5_9_9_2, 0.6_4_9_5, -3.8_3_3_6, 1.6_0_2_5, -3.2_8_1_7, 0.1_7_2_1, -0.0_6_3_3, 1.7_5_1_6, 2.7_0_3_9, 0.8_1_0_0, -0.5_9_0_8, -3.2_1_1_3, -4.4_3_4_3, 2.9_2_5_7, 1.3_6_3_2, 1.5_5_6_2, -2.1_4_8_9, -1.9_8_9_4, 3.0_5_6_0, 3.3_3_9_6, -0.7_3_2_8, -1.0_4_1_7, 0.0_3_8_3, 3.7_0_9_3, 3.2_3_4_3 ]) __snake_case = torch.tensor([ -1.4_5_7_4, -2.0_5_6_9, -0.0_4_7_3, -0.6_1_1_7, 1.4_0_1_8, 0.5_7_6_9, 0.4_1_2_9, -2.7_3_4_4, 1.2_2_4_1, -2.1_3_9_7, 0.2_0_0_0, 0.3_9_3_7, 0.7_6_1_6, 2.0_4_5_3, 0.7_3_2_4, -0.3_3_9_1, -2.1_7_4_6, -2.7_7_4_4, 1.6_9_6_3, 0.6_9_2_1, 1.2_1_8_7, -1.6_1_7_2, -0.8_8_7_7, 2.2_4_3_9, 1.8_4_7_1, -0.5_8_3_9, -0.5_6_0_5, -0.0_4_6_4, 2.3_2_5_0, 2.1_2_1_9 ]) # fmt: on __snake_case = api.list_models(filter="""diffusers""") for mod in models: if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256": __snake_case = """/home/patrick/google_checkpoints/""" + mod.modelId.split("""/""")[-1] print(f'''Started running {mod.modelId}!!!''') if mod.modelId.startswith("""CompVis"""): __snake_case = UNetaDModel.from_pretrained(local_checkpoint, subfolder="""unet""") else: __snake_case = UNetaDModel.from_pretrained(local_checkpoint) torch.manual_seed(0) random.seed(0) __snake_case = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size) __snake_case = torch.tensor([10] * noise.shape[0]) with torch.no_grad(): __snake_case = model(noise, time_step).sample assert torch.allclose( logits[0, 0, 0, :30], results["""_""".join("""_""".join(mod.modelId.split("""/""")).split("""-"""))], atol=1E-3 ) print(f'''{mod.modelId} has passed successfully!!!''')
259
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase :List[str] = True for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase :List[Any] = True if a[i].islower(): UpperCamelCase :List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
259
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/config.json""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/config.json""" # See all FNet models at https://huggingface.co/models?filter=fnet } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Union[str, Any] ='fnet' def __init__( self , SCREAMING_SNAKE_CASE_=3_2000 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu_new" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ) -> int: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = vocab_size UpperCamelCase :Optional[int] = max_position_embeddings UpperCamelCase :Tuple = hidden_size UpperCamelCase :Tuple = num_hidden_layers UpperCamelCase :Optional[Any] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :str = hidden_dropout_prob UpperCamelCase :Optional[int] = initializer_range UpperCamelCase :int = type_vocab_size UpperCamelCase :Optional[int] = layer_norm_eps UpperCamelCase :str = use_tpu_fourier_optimizations UpperCamelCase :Union[str, Any] = tpu_short_seq_length
259
from math import factorial __snake_case = {str(digit): factorial(digit) for digit in range(10)} def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(SCREAMING_SNAKE_CASE__ ) ) def _A ( SCREAMING_SNAKE_CASE__ : int = 60 , SCREAMING_SNAKE_CASE__ : int = 1000000 ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length UpperCamelCase :Any = 0 # the cached sizes of the previous chains UpperCamelCase :dict[int, int] = {} for start_chain_element in range(1 , SCREAMING_SNAKE_CASE__ ): # The temporary set will contain the elements of the chain UpperCamelCase :List[Any] = set() UpperCamelCase :Any = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. UpperCamelCase :Optional[Any] = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(SCREAMING_SNAKE_CASE__ ) chain_set_length += 1 UpperCamelCase :List[Any] = digit_factorial_sum(SCREAMING_SNAKE_CASE__ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] UpperCamelCase :Any = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution()}''')
259
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __snake_case = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class UpperCAmelCase_ ( datasets.BuilderConfig ): """simple docstring""" UpperCamelCase_ : Optional[datasets.Features] =None def _A ( SCREAMING_SNAKE_CASE__ : "pyspark.sql.DataFrame" , SCREAMING_SNAKE_CASE__ : List[int] , ): import pyspark def generate_fn(): UpperCamelCase :str = df.select('''*''' , pyspark.sql.functions.spark_partition_id().alias('''part_id''' ) ) for partition_id in partition_order: UpperCamelCase :Any = df_with_partition_id.select('''*''' ).where(F'''part_id = {partition_id}''' ).drop('''part_id''' ) UpperCamelCase :List[Any] = partition_df.collect() UpperCamelCase :str = 0 for row in rows: yield F'''{partition_id}_{row_id}''', row.asDict() row_id += 1 return generate_fn class UpperCAmelCase_ ( _BaseExamplesIterable ): """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , ) -> str: UpperCamelCase :Optional[Any] = df UpperCamelCase :Tuple = partition_order or range(self.df.rdd.getNumPartitions() ) UpperCamelCase :List[Any] = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self ) -> Any: yield from self.generate_examples_fn() def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> "SparkExamplesIterable": UpperCamelCase :str = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(SCREAMING_SNAKE_CASE_ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> "SparkExamplesIterable": UpperCamelCase :Union[str, Any] = self.split_shard_indices_by_worker(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return SparkExamplesIterable(self.df , partition_order=SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase ( self ) -> int: return len(self.partition_order ) class UpperCAmelCase_ ( datasets.DatasetBuilder ): """simple docstring""" UpperCamelCase_ : Union[str, Any] =SparkConfig def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: import pyspark UpperCamelCase :Any = pyspark.sql.SparkSession.builder.getOrCreate() UpperCamelCase :List[str] = df UpperCamelCase :Optional[int] = working_dir super().__init__( cache_dir=SCREAMING_SNAKE_CASE_ , config_name=str(self.df.semanticHash() ) , **SCREAMING_SNAKE_CASE_ , ) def UpperCAmelCase ( self ) -> str: # Returns the path of the created file. def create_cache_and_write_probe(SCREAMING_SNAKE_CASE_ ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = os.path.join(self._cache_dir , '''fs_test''' + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(SCREAMING_SNAKE_CASE_ , '''a''' ) return [probe_file] if self._spark.conf.get('''spark.master''' , '''''' ).startswith('''local''' ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: UpperCamelCase :Dict = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(SCREAMING_SNAKE_CASE_ ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( '''When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir''' ) def UpperCAmelCase ( self ) -> Optional[Any]: return datasets.DatasetInfo(features=self.config.features ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Tuple: import pyspark def get_arrow_batch_size(SCREAMING_SNAKE_CASE_ ): for batch in it: yield pa.RecordBatch.from_pydict({'''batch_bytes''': [batch.nbytes]} ) UpperCamelCase :List[Any] = self.df.count() UpperCamelCase :str = df_num_rows if df_num_rows <= 100 else 100 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. UpperCamelCase :Dict = ( self.df.limit(SCREAMING_SNAKE_CASE_ ) .repartition(1 ) .mapInArrow(SCREAMING_SNAKE_CASE_ , '''batch_bytes: long''' ) .agg(pyspark.sql.functions.sum('''batch_bytes''' ).alias('''sample_bytes''' ) ) .collect()[0] .sample_bytes / sample_num_rows ) UpperCamelCase :Tuple = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. UpperCamelCase :List[Any] = min(SCREAMING_SNAKE_CASE_ , int(approx_total_size / max_shard_size ) ) UpperCamelCase :Tuple = self.df.repartition(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ) -> Iterable[Tuple[int, bool, Union[int, tuple]]]: import pyspark UpperCamelCase :Any = ParquetWriter if file_format == '''parquet''' else ArrowWriter UpperCamelCase :Optional[int] = os.path.join(self._working_dir , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) if self._working_dir else fpath UpperCamelCase :int = file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. UpperCamelCase :str = self.config.features UpperCamelCase :Tuple = self._writer_batch_size UpperCamelCase :List[str] = self._fs.storage_options def write_arrow(SCREAMING_SNAKE_CASE_ ): # Within the same SparkContext, no two task attempts will share the same attempt ID. UpperCamelCase :List[Any] = pyspark.TaskContext().taskAttemptId() UpperCamelCase :Optional[int] = next(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) UpperCamelCase :Dict = 0 UpperCamelCase :int = writer_class( features=SCREAMING_SNAKE_CASE_ , path=working_fpath.replace('''SSSSS''' , F'''{shard_id:05d}''' ).replace('''TTTTT''' , F'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE_ , storage_options=SCREAMING_SNAKE_CASE_ , embed_local_files=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Tuple = pa.Table.from_batches([first_batch] ) writer.write_table(SCREAMING_SNAKE_CASE_ ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: UpperCamelCase , UpperCamelCase :int = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) shard_id += 1 UpperCamelCase :List[str] = writer_class( features=writer._features , path=working_fpath.replace('''SSSSS''' , F'''{shard_id:05d}''' ).replace('''TTTTT''' , F'''{task_id:05d}''' ) , writer_batch_size=SCREAMING_SNAKE_CASE_ , storage_options=SCREAMING_SNAKE_CASE_ , embed_local_files=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Optional[Any] = pa.Table.from_batches([batch] ) writer.write_table(SCREAMING_SNAKE_CASE_ ) if writer._num_bytes > 0: UpperCamelCase , UpperCamelCase :Union[str, Any] = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=['''task_id''', '''num_examples''', '''num_bytes'''] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Optional[int] = os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE_ ) , os.path.basename(SCREAMING_SNAKE_CASE_ ) ) shutil.move(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = ( self.df.mapInArrow(SCREAMING_SNAKE_CASE_ , '''task_id: long, num_examples: long, num_bytes: long''' ) .groupBy('''task_id''' ) .agg( pyspark.sql.functions.sum('''num_examples''' ).alias('''total_num_examples''' ) , pyspark.sql.functions.sum('''num_bytes''' ).alias('''total_num_bytes''' ) , pyspark.sql.functions.count('''num_bytes''' ).alias('''num_shards''' ) , pyspark.sql.functions.collect_list('''num_examples''' ).alias('''shard_lengths''' ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = "arrow" , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> int: self._validate_cache_dir() UpperCamelCase :Tuple = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = not is_remote_filesystem(self._fs ) UpperCamelCase :str = os.path.join if is_local else posixpath.join UpperCamelCase :Union[str, Any] = '''-TTTTT-SSSSS-of-NNNNN''' UpperCamelCase :str = F'''{self.name}-{split_generator.name}{SUFFIX}.{file_format}''' UpperCamelCase :Any = path_join(self._output_dir , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = 0 UpperCamelCase :Union[str, Any] = 0 UpperCamelCase :int = 0 UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Optional[Any] = [] for task_id, content in self._prepare_split_single(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :int = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = total_num_examples UpperCamelCase :Dict = total_num_bytes # should rename everything at the end logger.debug(F'''Renaming {total_shards} shards.''' ) if total_shards > 1: UpperCamelCase :Tuple = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. UpperCamelCase :Tuple = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , ): rename( SCREAMING_SNAKE_CASE_ , fpath.replace('''SSSSS''' , F'''{shard_id:05d}''' ).replace('''TTTTT''' , F'''{task_id:05d}''' ) , fpath.replace('''TTTTT-SSSSS''' , F'''{global_shard_id:05d}''' ).replace('''NNNNN''' , F'''{total_shards:05d}''' ) , ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :List[str] = 0 for i in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase , UpperCamelCase :List[str] = task_id_and_num_shards[i] for shard_id in range(SCREAMING_SNAKE_CASE_ ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(SCREAMING_SNAKE_CASE_ , len(SCREAMING_SNAKE_CASE_ ) ).map(lambda SCREAMING_SNAKE_CASE_ : _rename_shard(*SCREAMING_SNAKE_CASE_ ) ).collect() else: # don't use any pattern UpperCamelCase :List[Any] = 0 UpperCamelCase :Union[str, Any] = task_id_and_num_shards[0][0] self._rename( fpath.replace('''SSSSS''' , F'''{shard_id:05d}''' ).replace('''TTTTT''' , F'''{task_id:05d}''' ) , fpath.replace(SCREAMING_SNAKE_CASE_ , '''''' ) , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , ) -> SparkExamplesIterable: return SparkExamplesIterable(self.df )
259
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ ( lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : int =DDIMPipeline UpperCamelCase_ : str =UNCONDITIONAL_IMAGE_GENERATION_PARAMS UpperCamelCase_ : str =PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } UpperCamelCase_ : Optional[Any] =UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS UpperCamelCase_ : List[str] =False def UpperCAmelCase ( self ) -> Any: torch.manual_seed(0 ) UpperCamelCase :Optional[int] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Any = {'''unet''': unet, '''scheduler''': scheduler} return components def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Any: if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): UpperCamelCase :List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase :List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Optional[int] = '''cpu''' UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Optional[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase :str = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) UpperCamelCase :Tuple = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) UpperCamelCase :List[str] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def UpperCAmelCase ( self ) -> int: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Optional[int]: super().test_save_load_local(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Any: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = '''google/ddpm-cifar10-32''' UpperCamelCase :Union[str, Any] = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Tuple = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddim.to(SCREAMING_SNAKE_CASE_ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddim(generator=SCREAMING_SNAKE_CASE_ , eta=0.0 , output_type='''numpy''' ).images UpperCamelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :Tuple = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[Any] = '''google/ddpm-ema-bedroom-256''' UpperCamelCase :Any = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddpm.to(SCREAMING_SNAKE_CASE_ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddpm(generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCamelCase :Dict = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
259
1
from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal __snake_case = logging.get_logger(__name__) __snake_case = TypeVar("""DatasetType""", Dataset, IterableDataset) def _A ( SCREAMING_SNAKE_CASE__ : List[DatasetType] , SCREAMING_SNAKE_CASE__ : Optional[List[float]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[DatasetInfo] = None , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ): from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , (Dataset, IterableDataset) ): if isinstance(SCREAMING_SNAKE_CASE__ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' '''is an empty dataset dictionary.''' ) raise ValueError( F'''Dataset at position {i} has at least one split: {list(SCREAMING_SNAKE_CASE__ )}\n''' F'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(SCREAMING_SNAKE_CASE__ ) )}\']''' ) raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(SCREAMING_SNAKE_CASE__ ).__name__}.''' ) if i == 0: UpperCamelCase , UpperCamelCase :Dict = ( (Dataset, IterableDataset) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else (IterableDataset, Dataset) ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError( F'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F'''{stopping_strategy} is not supported. Please enter a valid stopping_strategy.''' ) if dataset_type is Dataset: return _interleave_map_style_datasets( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , info=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , stopping_strategy=SCREAMING_SNAKE_CASE__ ) else: return _interleave_iterable_datasets( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , info=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , stopping_strategy=SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : List[DatasetType] , SCREAMING_SNAKE_CASE__ : Optional[DatasetInfo] = None , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : int = 0 , ): if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , (Dataset, IterableDataset) ): if isinstance(SCREAMING_SNAKE_CASE__ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' '''is an empty dataset dictionary.''' ) raise ValueError( F'''Dataset at position {i} has at least one split: {list(SCREAMING_SNAKE_CASE__ )}\n''' F'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(SCREAMING_SNAKE_CASE__ ) )}\']''' ) raise ValueError( F'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(SCREAMING_SNAKE_CASE__ ).__name__}.''' ) if i == 0: UpperCamelCase , UpperCamelCase :Dict = ( (Dataset, IterableDataset) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else (IterableDataset, Dataset) ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError( F'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(SCREAMING_SNAKE_CASE__ , info=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , axis=SCREAMING_SNAKE_CASE__ ) else: return _concatenate_iterable_datasets(SCREAMING_SNAKE_CASE__ , info=SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , axis=SCREAMING_SNAKE_CASE__ )
259
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _A ( SCREAMING_SNAKE_CASE__ : str = "isbn/0140328726" ): UpperCamelCase :Optional[int] = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' ) != 1: UpperCamelCase :str = F'''{olid} is not a valid Open Library olid''' raise ValueError(SCREAMING_SNAKE_CASE__ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def _A ( SCREAMING_SNAKE_CASE__ : dict ): UpperCamelCase :str = { '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } UpperCamelCase :Optional[Any] = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} UpperCamelCase :List[str] = [ get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors'''] ] UpperCamelCase :int = data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[str] = ''', '''.join(SCREAMING_SNAKE_CASE__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: __snake_case = input("""\nEnter the ISBN code to search (or 'quit' to stop): """).strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: __snake_case = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print("""\n""".join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
259
1
import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def _A ( ): UpperCamelCase :Optional[int] = ArgumentParser( description=( '''PyTorch TPU distributed training launch ''' '''helper utility that will spawn up ''' '''multiple distributed processes''' ) ) # Optional arguments for the launch helper parser.add_argument('''--num_cores''' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='''Number of TPU cores to use (1 or 8).''' ) # positional parser.add_argument( '''training_script''' , type=SCREAMING_SNAKE_CASE__ , help=( '''The full path to the single TPU training ''' '''program/script to be launched in parallel, ''' '''followed by all the arguments for the ''' '''training script''' ) , ) # rest from the training program parser.add_argument('''training_script_args''' , nargs=SCREAMING_SNAKE_CASE__ ) return parser.parse_args() def _A ( ): UpperCamelCase :Union[str, Any] = parse_args() # Import training_script as a module. UpperCamelCase :int = Path(args.training_script ) sys.path.append(str(script_fpath.parent.resolve() ) ) UpperCamelCase :Tuple = script_fpath.stem UpperCamelCase :Any = importlib.import_module(SCREAMING_SNAKE_CASE__ ) # Patch sys.argv UpperCamelCase :Optional[int] = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )] xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores ) if __name__ == "__main__": main()
259
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin __snake_case = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=14 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=[1, 2, 3, 4, 5] , SCREAMING_SNAKE_CASE_=25 , SCREAMING_SNAKE_CASE_=5 , ) -> str: UpperCamelCase :Any = d_model UpperCamelCase :List[str] = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :str = prediction_length UpperCamelCase :str = context_length UpperCamelCase :int = cardinality UpperCamelCase :Optional[Any] = num_time_features UpperCamelCase :Optional[Any] = lags_sequence UpperCamelCase :str = embedding_dimension UpperCamelCase :str = is_training UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :int = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :Optional[int] = context_length UpperCamelCase :Tuple = prediction_length + label_length UpperCamelCase :Optional[Any] = label_length UpperCamelCase :Optional[int] = moving_average UpperCamelCase :Union[str, Any] = autocorrelation_factor def UpperCAmelCase ( self ) -> Optional[int]: return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :Optional[Any] = config.context_length + max(config.lags_sequence ) UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) UpperCamelCase :List[str] = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) UpperCamelCase :Union[str, Any] = floats_tensor([self.batch_size, _past_length] ) UpperCamelCase :Any = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs UpperCamelCase :Tuple = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) UpperCamelCase :int = floats_tensor([self.batch_size, config.prediction_length] ) UpperCamelCase :Union[str, Any] = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :int = self.get_config() UpperCamelCase :Union[str, Any] = self.prepare_autoformer_inputs_dict(SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def UpperCAmelCase ( self ) -> Any: UpperCamelCase , UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCamelCase :int = AutoformerModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase :Any = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = outputs.encoder_last_hidden_state UpperCamelCase :str = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Any = model.get_encoder() encoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = AutoformerEncoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = model.create_network_inputs(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) UpperCamelCase :Tuple = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) UpperCamelCase :Optional[Any] = encoder(inputs_embeds=SCREAMING_SNAKE_CASE_ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) UpperCamelCase :Optional[Any] = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) UpperCamelCase :Union[str, Any] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) UpperCamelCase :Tuple = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) UpperCamelCase :Optional[Any] = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Union[str, Any] = model.get_decoder() decoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoformerDecoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = decoder( trend=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[str] =(AutoformerModel, AutoformerForPrediction) if is_torch_available() else () UpperCamelCase_ : List[str] =(AutoformerForPrediction,) if is_torch_available() else () UpperCamelCase_ : Optional[Any] ={'feature-extraction': AutoformerModel} if is_torch_available() else {} UpperCamelCase_ : Any =False UpperCamelCase_ : List[str] =False UpperCamelCase_ : Dict =False UpperCamelCase_ : Dict =False UpperCamelCase_ : int =False UpperCamelCase_ : Optional[int] =False def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = AutoformerModelTester(self ) UpperCamelCase :int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase , UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: UpperCamelCase :Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :List[str] = model_class.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertEqual(info['''missing_keys'''] , [] ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = inspect.signature(getattr(SCREAMING_SNAKE_CASE_ , '''forward''' ) ) # The main input is the name of the argument after `self` UpperCamelCase :List[str] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Tuple = [*signature.parameters.keys()] UpperCamelCase :Optional[Any] = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(SCREAMING_SNAKE_CASE_ )] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = True UpperCamelCase :Dict = getattr(self.model_tester , '''seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = getattr(self.model_tester , '''decoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = getattr(self.model_tester , '''encoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = getattr(self.model_tester , '''d_model''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = getattr(self.model_tester , '''num_attention_heads''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = d_model // num_attention_heads for model_class in self.all_model_classes: UpperCamelCase :Tuple = True UpperCamelCase :Tuple = False UpperCamelCase :Any = True UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :int = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # decoder attentions UpperCamelCase :Union[str, Any] = outputs.decoder_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions UpperCamelCase :Union[str, Any] = outputs.cross_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine UpperCamelCase :Any = True UpperCamelCase :int = True UpperCamelCase :Any = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(out_len + 2 , len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def UpperCAmelCase ( self ) -> List[Any]: super().test_retain_grad_hidden_states_attentions() def _A ( SCREAMING_SNAKE_CASE__ : int="train-batch.pt" ): UpperCamelCase :Union[str, Any] = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) UpperCamelCase :Tuple = torch.load(SCREAMING_SNAKE_CASE__ , map_location=SCREAMING_SNAKE_CASE__ ) return batch @require_torch @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :int = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = prepare_batch() with torch.no_grad(): UpperCamelCase :Optional[Any] = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] UpperCamelCase :Union[str, Any] = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Dict = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state UpperCamelCase :Union[str, Any] = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Tuple = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) UpperCamelCase :Optional[int] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , SCREAMING_SNAKE_CASE_ , rtol=1e-1 ) )
259
1
import requests from bsa import BeautifulSoup def _A ( SCREAMING_SNAKE_CASE__ : str = "AAPL" ): UpperCamelCase :str = F'''https://in.finance.yahoo.com/quote/{symbol}?s={symbol}''' UpperCamelCase :int = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , '''html.parser''' ) UpperCamelCase :Optional[int] = '''My(6px) Pos(r) smartphone_Mt(6px)''' return soup.find('''div''' , class_=class_ ).find('''span''' ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(f'''Current {symbol:<4} stock price is {stock_price(symbol):>8}''')
259
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed __snake_case = logging.getLogger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : Dict=2 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Any=16 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 2 ): def get_dataset(SCREAMING_SNAKE_CASE__ : List[Any] ): UpperCamelCase :Union[str, Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(SCREAMING_SNAKE_CASE__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) UpperCamelCase :str = get_dataset(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = get_dataset(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) UpperCamelCase :Any = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=None ): UpperCamelCase :Dict = [] for epoch in range(SCREAMING_SNAKE_CASE__ ): # Train quickly model.train() for batch in dataloader: UpperCamelCase , UpperCamelCase :Optional[Any] = batch UpperCamelCase :int = model(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) accelerator.backward(SCREAMING_SNAKE_CASE__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self ) -> str: super().__init__() UpperCamelCase :Optional[int] = nn.Parameter(torch.randn(1 ) ) UpperCamelCase :int = nn.Parameter(torch.randn(1 ) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return x * self.a + self.b class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Dict: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Tuple = dummy_dataloaders() UpperCamelCase :Tuple = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :Dict = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def UpperCAmelCase ( self ) -> str: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[str] = DummyModel() UpperCamelCase :Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Dict = dummy_dataloaders() # Train baseline UpperCamelCase :Dict = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial UpperCamelCase :int = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[Any] = model.a.item(), model.b.item() UpperCamelCase :Optional[int] = optimizer.state_dict() UpperCamelCase :Optional[int] = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Dict = model.a.item(), model.b.item() UpperCamelCase :Optional[Any] = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase :Any = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :List[Any] = dummy_dataloaders() UpperCamelCase :List[str] = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Tuple = model.a.item(), model.b.item() UpperCamelCase :Tuple = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything UpperCamelCase :Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Union[str, Any] = model.a.item(), model.b.item() UpperCamelCase :Optional[Any] = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[Any] = DummyModel() UpperCamelCase :Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :int = dummy_dataloaders() UpperCamelCase :int = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :Union[str, Any] = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((UpperCamelCase) , (UpperCamelCase)) :List[str] = model.a.item(), model.b.item() UpperCamelCase :Dict = optimizer.state_dict() UpperCamelCase :Any = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[int] = model.a.item(), model.b.item() UpperCamelCase :Any = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase :Union[str, Any] = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Tuple = dummy_dataloaders() UpperCamelCase :Optional[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((UpperCamelCase) , (UpperCamelCase)) :Dict = model.a.item(), model.b.item() UpperCamelCase :Dict = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[Any] = model.a.item(), model.b.item() UpperCamelCase :str = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[Any] = torch.tensor([1, 2, 3] ) UpperCamelCase :Any = torch.tensor([2, 3, 4] ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :Optional[Any] = torch.optim.Adam(net.parameters() ) UpperCamelCase :Optional[Any] = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def UpperCAmelCase ( self ) -> Any: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[Any] = DummyModel() UpperCamelCase :List[str] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase :Any = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) UpperCamelCase , UpperCamelCase :Any = dummy_dataloaders() UpperCamelCase :Optional[int] = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :str = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() UpperCamelCase :int = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def UpperCAmelCase ( self ) -> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :int = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline UpperCamelCase :Tuple = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''torchrun''', F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": __snake_case = """/tmp/accelerate/state_checkpointing""" __snake_case = DummyModel() __snake_case = torch.optim.Adam(params=model.parameters(), lr=1E-3) __snake_case = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9) __snake_case , __snake_case = dummy_dataloaders() __snake_case = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline __snake_case = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""") if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) __snake_case , __snake_case , __snake_case , __snake_case , __snake_case = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) __snake_case , __snake_case = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert param_device.type == accelerator.device.type __snake_case = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""") for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert ( param_device.type == torch.device("""cpu""").type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""") for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""): accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""") accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
259
1
from __future__ import annotations def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Optional[int] = get_failure_array(SCREAMING_SNAKE_CASE__ ) # 2) Step through text searching for pattern UpperCamelCase , UpperCamelCase :Any = 0, 0 # index into text, pattern while i < len(SCREAMING_SNAKE_CASE__ ): if pattern[j] == text[i]: if j == (len(SCREAMING_SNAKE_CASE__ ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: UpperCamelCase :List[Any] = failure[j - 1] continue i += 1 return False def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :str = [0] UpperCamelCase :List[str] = 0 UpperCamelCase :Optional[int] = 1 while j < len(SCREAMING_SNAKE_CASE__ ): if pattern[i] == pattern[j]: i += 1 elif i > 0: UpperCamelCase :Optional[int] = failure[i - 1] continue j += 1 failure.append(SCREAMING_SNAKE_CASE__ ) return failure if __name__ == "__main__": # Test 1) __snake_case = """abc1abc12""" __snake_case = """alskfjaldsabc1abc1abc12k23adsfabcabc""" __snake_case = """alskfjaldsk23adsfabcabc""" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) __snake_case = """ABABX""" __snake_case = """ABABZABABYABABX""" assert kmp(pattern, text) # Test 3) __snake_case = """AAAB""" __snake_case = """ABAAAAAB""" assert kmp(pattern, text) # Test 4) __snake_case = """abcdabcy""" __snake_case = """abcxabcdabxabcdabcdabcy""" assert kmp(pattern, text) # Test 5) __snake_case = """aabaabaaa""" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
259
import numpy as np __snake_case = [ ["""a""", """b""", """c""", """d""", """e"""], ["""f""", """g""", """h""", """i""", """k"""], ["""l""", """m""", """n""", """o""", """p"""], ["""q""", """r""", """s""", """t""", """u"""], ["""v""", """w""", """x""", """y""", """z"""], ] class UpperCAmelCase_ : """simple docstring""" def __init__( self ) -> None: UpperCamelCase :Dict = np.array(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> np.ndarray: UpperCamelCase , UpperCamelCase :Tuple = np.where(letter == self.SQUARE ) UpperCamelCase :List[Any] = np.concatenate([indexa + 1, indexa + 1] ) return indexes def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :int = self.SQUARE[indexa - 1, indexa - 1] return letter def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Any = message.lower() UpperCamelCase :int = message.replace(''' ''' , '''''' ) UpperCamelCase :Dict = message.replace('''j''' , '''i''' ) UpperCamelCase :str = np.empty((2, len(SCREAMING_SNAKE_CASE_ )) ) for letter_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Dict = self.letter_to_numbers(message[letter_index] ) UpperCamelCase :Union[str, Any] = numbers[0] UpperCamelCase :Dict = numbers[1] UpperCamelCase :Any = first_step.reshape(2 * len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = '''''' for numbers_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Dict = int(second_step[numbers_index * 2] ) UpperCamelCase :List[str] = int(second_step[(numbers_index * 2) + 1] ) UpperCamelCase :Tuple = self.numbers_to_letter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = encoded_message + letter return encoded_message def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Any = message.lower() message.replace(''' ''' , '''''' ) UpperCamelCase :Optional[int] = np.empty(2 * len(SCREAMING_SNAKE_CASE_ ) ) for letter_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :List[str] = self.letter_to_numbers(message[letter_index] ) UpperCamelCase :Dict = numbers[0] UpperCamelCase :List[str] = numbers[1] UpperCamelCase :int = first_step.reshape((2, len(SCREAMING_SNAKE_CASE_ )) ) UpperCamelCase :Any = '''''' for numbers_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Any = int(second_step[0, numbers_index] ) UpperCamelCase :List[Any] = int(second_step[1, numbers_index] ) UpperCamelCase :Tuple = self.numbers_to_letter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = decoded_message + letter return decoded_message
259
1
import math def _A ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): return math.pow(SCREAMING_SNAKE_CASE__ , 2 ) - a def _A ( SCREAMING_SNAKE_CASE__ : float ): return 2 * x def _A ( SCREAMING_SNAKE_CASE__ : float ): UpperCamelCase :List[str] = 2.0 while start <= a: UpperCamelCase :List[str] = math.pow(SCREAMING_SNAKE_CASE__ , 2 ) return start def _A ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : int = 9999 , SCREAMING_SNAKE_CASE__ : float = 0.00_00_00_00_00_00_01 ): if a < 0: raise ValueError('''math domain error''' ) UpperCamelCase :Optional[int] = get_initial_point(SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :str = value UpperCamelCase :Tuple = value - fx(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) / fx_derivative(SCREAMING_SNAKE_CASE__ ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
259
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple ): return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any="attention" ): UpperCamelCase :str = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) UpperCamelCase :Optional[Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase :Optional[int] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) UpperCamelCase :List[Any] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase :Union[str, Any] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) UpperCamelCase :Any = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase :str = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) UpperCamelCase :str = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str]=False ): if split_mlp_wi: UpperCamelCase :List[Any] = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] UpperCamelCase :int = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] UpperCamelCase :str = (wi_a, wi_a) else: UpperCamelCase :Optional[Any] = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] UpperCamelCase :Optional[int] = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ): return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def _A ( SCREAMING_SNAKE_CASE__ : dict , *, SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : bool = False ): UpperCamelCase :Tuple = traverse_util.flatten_dict(variables['''target'''] ) UpperCamelCase :List[Any] = {'''/'''.join(SCREAMING_SNAKE_CASE__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :int = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = collections.OrderedDict() # Shared embeddings. UpperCamelCase :int = old['''token_embedder/embedding'''] # Encoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :str = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''pre_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''attention''' ) UpperCamelCase :str = layer_norm UpperCamelCase :Dict = k.T UpperCamelCase :Optional[Any] = o.T UpperCamelCase :int = q.T UpperCamelCase :Any = v.T # Block i, layer 1 (MLP). UpperCamelCase :Tuple = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase , UpperCamelCase :Any = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = layer_norm if split_mlp_wi: UpperCamelCase :List[Any] = wi[0].T UpperCamelCase :Tuple = wi[1].T else: UpperCamelCase :Optional[Any] = wi.T UpperCamelCase :Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :List[str] = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' ).T UpperCamelCase :Optional[Any] = old['''encoder/encoder_norm/scale'''] if not scalable_attention: UpperCamelCase :str = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , '''encoder''' ).T UpperCamelCase :Any = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Union[str, Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_self_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''self_attention''' ) UpperCamelCase :str = layer_norm UpperCamelCase :int = k.T UpperCamelCase :Optional[int] = o.T UpperCamelCase :Tuple = q.T UpperCamelCase :List[str] = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :str = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''encoder_decoder_attention''' ) UpperCamelCase :Tuple = layer_norm UpperCamelCase :Optional[Any] = k.T UpperCamelCase :List[str] = o.T UpperCamelCase :List[str] = q.T UpperCamelCase :str = v.T # Block i, layer 2 (MLP). UpperCamelCase :List[str] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase , UpperCamelCase :Optional[int] = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = layer_norm if split_mlp_wi: UpperCamelCase :List[str] = wi[0].T UpperCamelCase :str = wi[1].T else: UpperCamelCase :Dict = wi.T UpperCamelCase :Optional[Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Tuple = tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' ).T UpperCamelCase :Union[str, Any] = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Union[str, Any] = old['''decoder/logits_dense/kernel'''].T return new def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : bool ): UpperCamelCase :Optional[int] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Dict = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Dict = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) UpperCamelCase :List[Any] = state_dict['''shared.weight'''] return state_dict def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ): UpperCamelCase :Dict = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = convert_tax_to_pytorch( SCREAMING_SNAKE_CASE__ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE__ , scalable_attention=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = make_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ): UpperCamelCase :Any = MTaConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase :List[str] = UMTaEncoderModel(SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase :Any = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE__ ) print('''Done''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""") # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False ) parser.add_argument( """--scalable_attention""", action="""store_true""", help="""Whether the model uses scaled attention (umt5 model)""", default=False, ) __snake_case = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
259
1
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase ( self ) -> Union[str, Any]: torch.manual_seed(0 ) UpperCamelCase :Dict = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Optional[Any] = self.dummy_uncond_unet UpperCamelCase :Optional[Any] = PNDMScheduler() UpperCamelCase :List[str] = PNDMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) pndm.to(SCREAMING_SNAKE_CASE_ ) pndm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = torch.manual_seed(0 ) UpperCamelCase :List[str] = pndm(generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=20 , output_type='''numpy''' ).images UpperCamelCase :Union[str, Any] = torch.manual_seed(0 ) UpperCamelCase :Optional[Any] = pndm(generator=SCREAMING_SNAKE_CASE_ , num_inference_steps=20 , output_type='''numpy''' , return_dict=SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase :int = image[0, -3:, -3:, -1] UpperCamelCase :List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :Tuple = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Any = '''google/ddpm-cifar10-32''' UpperCamelCase :int = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = PNDMScheduler() UpperCamelCase :Optional[int] = PNDMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) pndm.to(SCREAMING_SNAKE_CASE_ ) pndm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = torch.manual_seed(0 ) UpperCamelCase :Union[str, Any] = pndm(generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images UpperCamelCase :Optional[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :List[str] = np.array([0.1564, 0.1_4645, 0.1406, 0.1_4715, 0.1_2425, 0.1_4045, 0.1_3115, 0.1_2175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
259
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] ): UpperCamelCase :Tuple = len(SCREAMING_SNAKE_CASE__ ) print('''The following activities are selected:''' ) # The first activity is always selected UpperCamelCase :Dict = 0 print(SCREAMING_SNAKE_CASE__ , end=''',''' ) # Consider rest of the activities for j in range(SCREAMING_SNAKE_CASE__ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(SCREAMING_SNAKE_CASE__ , end=''',''' ) UpperCamelCase :List[str] = j if __name__ == "__main__": import doctest doctest.testmod() __snake_case = [1, 3, 0, 5, 8, 5] __snake_case = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
259
1
import heapq import sys import numpy as np __snake_case = tuple[int, int] class UpperCAmelCase_ : """simple docstring""" def __init__( self ) -> Optional[Any]: UpperCamelCase :Any = [] UpperCamelCase :Any = set() def UpperCAmelCase ( self ) -> Dict: if not self.empty(): return self.elements[0][0] else: return float('''inf''' ) def UpperCAmelCase ( self ) -> Optional[Any]: return len(self.elements ) == 0 def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> List[str]: if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(SCREAMING_SNAKE_CASE_ ) else: # update # print("update", item) UpperCamelCase :Tuple = [] ((UpperCamelCase) , (UpperCamelCase)) :Optional[int] = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((UpperCamelCase) , (UpperCamelCase)) :int = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Dict: if item in self.set: self.set.remove(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = [] ((UpperCamelCase) , (UpperCamelCase)) :List[Any] = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((UpperCamelCase) , (UpperCamelCase)) :Tuple = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def UpperCAmelCase ( self ) -> Optional[int]: return self.elements[0][1] def UpperCAmelCase ( self ) -> Optional[int]: ((UpperCamelCase) , (UpperCamelCase)) :int = heapq.heappop(self.elements ) self.set.remove(SCREAMING_SNAKE_CASE_ ) return (priority, item) def _A ( SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : TPos ): # euclidean distance UpperCamelCase :Union[str, Any] = np.array(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = np.array(SCREAMING_SNAKE_CASE__ ) return np.linalg.norm(a - b ) def _A ( SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : TPos ): # integer division by time variable return consistent_heuristic(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) // t def _A ( SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : TPos ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _A ( SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : dict[TPos, float] ): UpperCamelCase :Optional[int] = g_function[start] + Wa * heuristics[i](SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return ans def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :Optional[int] = np.chararray((n, n) ) for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = '''*''' for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): if (j, (n - 1) - i) in blocks: UpperCamelCase :Optional[int] = '''#''' UpperCamelCase :List[str] = '''-''' UpperCamelCase :List[Any] = back_pointer[goal] while x != start: ((UpperCamelCase) , (UpperCamelCase)) :List[str] = x # print(x) UpperCamelCase :int = '''-''' UpperCamelCase :Optional[int] = back_pointer[x] UpperCamelCase :Optional[Any] = '''-''' for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(SCREAMING_SNAKE_CASE__ ): if (i, j) == (0, n - 1): print(grid[i][j] , end=''' ''' ) print('''<-- End position''' , end=''' ''' ) else: print(grid[i][j] , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) print('''PATH TAKEN BY THE ALGORITHM IS:-''' ) UpperCamelCase :Union[str, Any] = back_pointer[goal] while x != start: print(SCREAMING_SNAKE_CASE__ , end=''' ''' ) UpperCamelCase :Any = back_pointer[x] print(SCREAMING_SNAKE_CASE__ ) sys.exit() def _A ( SCREAMING_SNAKE_CASE__ : TPos ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] , ): for itera in range(SCREAMING_SNAKE_CASE__ ): open_list[itera].remove_element(SCREAMING_SNAKE_CASE__ ) # print("s", s) # print("j", j) ((UpperCamelCase) , (UpperCamelCase)) :Any = s UpperCamelCase :str = (x - 1, y) UpperCamelCase :Optional[int] = (x + 1, y) UpperCamelCase :str = (x, y + 1) UpperCamelCase :Any = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(SCREAMING_SNAKE_CASE__ ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = -1 UpperCamelCase :int = float('''inf''' ) if valid(SCREAMING_SNAKE_CASE__ ) and g_function[neighbours] > g_function[s] + 1: UpperCamelCase :str = g_function[s] + 1 UpperCamelCase :Any = s if neighbours not in close_list_anchor: open_list[0].put(SCREAMING_SNAKE_CASE__ , key(SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) if neighbours not in close_list_inad: for var in range(1 , SCREAMING_SNAKE_CASE__ ): if key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) <= Wa * key( SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): open_list[j].put( SCREAMING_SNAKE_CASE__ , key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) def _A ( ): UpperCamelCase :List[Any] = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list __snake_case = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} __snake_case = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] __snake_case = make_common_ground() __snake_case = blocks_blk # hyper parameters __snake_case = 1 __snake_case = 1 __snake_case = 20 __snake_case = 3 # one consistent and two other inconsistent # start and end destination __snake_case = (0, 0) __snake_case = (n - 1, n - 1) __snake_case = 1 def _A ( SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : TPos , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Any = {start: 0, goal: float('''inf''' )} UpperCamelCase :Any = {start: -1, goal: -1} UpperCamelCase :Tuple = [] UpperCamelCase :List[str] = set() for i in range(SCREAMING_SNAKE_CASE__ ): open_list.append(PriorityQueue() ) open_list[i].put(SCREAMING_SNAKE_CASE__ , key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) UpperCamelCase :list[int] = [] UpperCamelCase :list[int] = [] while open_list[0].minkey() < float('''inf''' ): for i in range(1 , SCREAMING_SNAKE_CASE__ ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float('''inf''' ): do_something(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase , UpperCamelCase :Tuple = open_list[i].top_show() visited.add(SCREAMING_SNAKE_CASE__ ) expand_state( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) close_list_inad.append(SCREAMING_SNAKE_CASE__ ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('''inf''' ): do_something(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase :str = open_list[0].top_show() visited.add(SCREAMING_SNAKE_CASE__ ) expand_state( SCREAMING_SNAKE_CASE__ , 0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) close_list_anchor.append(SCREAMING_SNAKE_CASE__ ) print('''No path found to goal''' ) print() for i in range(n - 1 , -1 , -1 ): for j in range(SCREAMING_SNAKE_CASE__ ): if (j, i) in blocks: print('''#''' , end=''' ''' ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print('''*''' , end=''' ''' ) else: print('''-''' , end=''' ''' ) else: print('''*''' , end=''' ''' ) if (j, i) == (n - 1, n - 1): print('''<-- End position''' , end=''' ''' ) print() print('''^''' ) print('''Start position''' ) print() print('''# is an obstacle''' ) print('''- is the path taken by algorithm''' ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
259
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Dict ='git_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_="quick_gelu" , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :Union[str, Any] = intermediate_size UpperCamelCase :Dict = num_hidden_layers UpperCamelCase :int = num_attention_heads UpperCamelCase :List[str] = num_channels UpperCamelCase :Optional[int] = patch_size UpperCamelCase :Optional[int] = image_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = attention_dropout UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :Optional[Any] = hidden_act @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :Dict = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from GITConfig if config_dict.get('''model_type''' ) == "git": UpperCamelCase :Tuple = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='git' def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=3_0522 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=6 , 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_=1024 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=101 , SCREAMING_SNAKE_CASE_=102 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> int: super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if vision_config is None: UpperCamelCase :Tuple = {} logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''' ) UpperCamelCase :Union[str, Any] = GitVisionConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = vocab_size UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Dict = hidden_act UpperCamelCase :List[str] = intermediate_size UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :Optional[int] = attention_probs_dropout_prob UpperCamelCase :Optional[Any] = max_position_embeddings UpperCamelCase :Tuple = initializer_range UpperCamelCase :Any = layer_norm_eps UpperCamelCase :int = position_embedding_type UpperCamelCase :Dict = use_cache UpperCamelCase :Tuple = tie_word_embeddings UpperCamelCase :Union[str, Any] = num_image_with_embedding UpperCamelCase :Optional[int] = bos_token_id UpperCamelCase :List[Any] = eos_token_id def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCamelCase :Optional[int] = self.vision_config.to_dict() UpperCamelCase :int = self.__class__.model_type return output
259
1
def _A ( SCREAMING_SNAKE_CASE__ : int ): if number > 0: raise ValueError('''input must be a negative integer''' ) UpperCamelCase :str = len(bin(SCREAMING_SNAKE_CASE__ )[3:] ) UpperCamelCase :List[str] = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:] UpperCamelCase :Optional[int] = ( ( '''1''' + '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
259
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __snake_case = """__DUMMY_TRANSFORMERS_USER__""" __snake_case = """Dummy User""" __snake_case = """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""" __snake_case = """https://hub-ci.huggingface.co""" __snake_case = CI_HUB_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}""" __snake_case = CI_HUB_ENDPOINT + """/{repo_id}/resolve/{revision}/{filename}""" __snake_case = Path("""~/.huggingface/hub_ci_token""").expanduser() @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Tuple ): monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Any ): monkeypatch.setattr('''datasets.config.HF_ENDPOINT''' , SCREAMING_SNAKE_CASE__ ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : List[str] ): monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] ): HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def _A ( ): return HfApi(endpoint=SCREAMING_SNAKE_CASE__ ) @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi ): UpperCamelCase :Tuple = HfFolder.get_token() HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Dict ): def _cleanup_repo(SCREAMING_SNAKE_CASE__ : Tuple ): hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Tuple ): @contextmanager def _temporary_repo(SCREAMING_SNAKE_CASE__ : Any ): try: yield repo_id finally: cleanup_repo(SCREAMING_SNAKE_CASE__ ) return _temporary_repo @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): UpperCamelCase :Union[str, Any] = F'''repo_txt_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :int = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data/text_data.txt''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ): UpperCamelCase :Optional[int] = F'''repo_zipped_txt_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :Any = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data.zip''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ): UpperCamelCase :Dict = F'''repo_zipped_img_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :Dict = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data.zip''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): return hf_private_dataset_repo_zipped_img_data_
259
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() __snake_case = logging.get_logger(__name__) __snake_case = """https://openaipublic.azureedge.net/jukebox/models/""" __snake_case = { """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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] ): if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :int = key.replace('''.model.1.bias''' , '''.conv1d_1.bias''' ) elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Union[str, Any] = key.replace('''.model.1.weight''' , '''.conv1d_1.weight''' ) elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[Any] = key.replace('''.model.3.bias''' , '''.conv1d_2.bias''' ) elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[int] = key.replace('''.model.3.weight''' , '''.conv1d_2.weight''' ) if "conditioner_blocks.0." in key: UpperCamelCase :Any = key.replace('''conditioner_blocks.0''' , '''conditioner_blocks''' ) if "prime_prior" in key: UpperCamelCase :int = 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 :Any = 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 :str = 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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Optional[int] = {} import re UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :str = re.compile( R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[int] = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[Any] = re.compile(R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = 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(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_encoder_block_conv_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :List[Any] = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_encoder_block_conv_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_encoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = regex_match.groups() UpperCamelCase :Any = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :Any = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :str = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' UpperCamelCase :List[str] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = prefix + resnet_block UpperCamelCase :str = re_encoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_proj_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_encoder_block_proj_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = regex_match.groups() UpperCamelCase :int = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' UpperCamelCase :str = re_encoder_block_proj_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = re_decoder_block_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :Optional[int] = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Any = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' UpperCamelCase :Optional[int] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Optional[int] = re_decoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_decoder_block_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = regex_match.groups() UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_decoder_block_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_prior_cond_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_prior_cond_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_prior_cond_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :Optional[Any] = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :int = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' UpperCamelCase :List[Any] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Dict = re_prior_cond_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[str] = re_prior_cond_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :Dict = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_prior_cond_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # keep original key else: UpperCamelCase :List[str] = original_key UpperCamelCase :Any = replace_key(SCREAMING_SNAKE_CASE__ ) 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 :Union[str, Any] = model_state_dict[F'''{key_prefix}.{key}'''] print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) UpperCamelCase :List[Any] = original_key UpperCamelCase :Any = original_key UpperCamelCase :Optional[int] = value return new_dict @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Dict=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): UpperCamelCase :Dict = requests.get(F'''{PREFIX}{file}''' , allow_redirects=SCREAMING_SNAKE_CASE__ ) os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=SCREAMING_SNAKE_CASE__ ) open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , '''wb''' ).write(r.content ) UpperCamelCase :Optional[int] = MODEL_MAPPING[model_name.split('''/''' )[-1]] UpperCamelCase :Any = JukeboxConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = JukeboxModel(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [] UpperCamelCase :List[Any] = {} for i, dict_name in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )['''model'''] UpperCamelCase :Tuple = {} for k in old_dic.keys(): if k.endswith('''.b''' ): UpperCamelCase :Optional[int] = old_dic[k] elif k.endswith('''.w''' ): UpperCamelCase :Optional[Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: UpperCamelCase :Optional[Any] = old_dic[k] else: UpperCamelCase :Any = old_dic[k] UpperCamelCase :Any = '''vqvae''' if i == 0 else F'''priors.{3 - i}''' UpperCamelCase :Dict = fix_jukebox_keys(SCREAMING_SNAKE_CASE__ , model.state_dict() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) weight_dict.append(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = weight_dict.pop(0 ) model.vqvae.load_state_dict(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) with open(F'''{pytorch_dump_folder_path}/mapping.json''' , '''w''' ) as txtfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) return weight_dict if __name__ == "__main__": __snake_case = 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.""", ) __snake_case = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
259
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , 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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> Dict: UpperCamelCase :Any = parent UpperCamelCase :Dict = 13 UpperCamelCase :List[Any] = 7 UpperCamelCase :List[Any] = True UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = True UpperCamelCase :List[str] = True UpperCamelCase :Dict = 99 UpperCamelCase :Any = 32 UpperCamelCase :Tuple = 2 UpperCamelCase :Union[str, Any] = 4 UpperCamelCase :List[str] = 37 UpperCamelCase :Dict = '''gelu''' UpperCamelCase :Dict = 0.1 UpperCamelCase :Tuple = 0.1 UpperCamelCase :Dict = 512 UpperCamelCase :str = 16 UpperCamelCase :Optional[Any] = 2 UpperCamelCase :Dict = 0.02 UpperCamelCase :Optional[int] = 3 UpperCamelCase :int = 4 UpperCamelCase :Dict = None def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Optional[int] = None if self.use_input_mask: UpperCamelCase :Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Dict = None if self.use_token_type_ids: UpperCamelCase :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Union[str, Any] = None UpperCamelCase :Optional[int] = None UpperCamelCase :Any = None if self.use_labels: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=SCREAMING_SNAKE_CASE_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_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_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = TFRoFormerModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} UpperCamelCase :int = [input_ids, input_mask] UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.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_ ) -> int: UpperCamelCase :List[Any] = True UpperCamelCase :Union[str, Any] = TFRoFormerForCausalLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Any = model(SCREAMING_SNAKE_CASE_ )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_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_ ) -> Union[str, Any]: UpperCamelCase :str = TFRoFormerForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_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_ ) -> List[str]: UpperCamelCase :List[Any] = self.num_labels UpperCamelCase :int = TFRoFormerForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Optional[Any] = model(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_ ) -> int: UpperCamelCase :List[Any] = self.num_choices UpperCamelCase :Any = TFRoFormerForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :int = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :Any = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :List[Any] = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) 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: UpperCamelCase :Union[str, Any] = self.num_labels UpperCamelCase :Dict = TFRoFormerForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.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_ ) -> Union[str, Any]: UpperCamelCase :Union[str, Any] = TFRoFormerForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(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 ) -> Tuple: UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : str =( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) UpperCamelCase_ : Tuple =( { 'feature-extraction': TFRoFormerModel, 'fill-mask': TFRoFormerForMaskedLM, 'question-answering': TFRoFormerForQuestionAnswering, 'text-classification': TFRoFormerForSequenceClassification, 'text-generation': TFRoFormerForCausalLM, 'token-classification': TFRoFormerForTokenClassification, 'zero-shot': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : Optional[Any] =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = TFRoFormerModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> List[str]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Tuple = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) UpperCamelCase :Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase :str = model(SCREAMING_SNAKE_CASE_ )[0] # TODO Replace vocab size UpperCamelCase :Tuple = 5_0000 UpperCamelCase :Optional[Any] = [1, 6, vocab_size] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. UpperCamelCase :int = tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =1E-4 def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :str = tf.constant([[4, 10]] ) UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) UpperCamelCase :str = emba(input_ids.shape ) UpperCamelCase :List[str] = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Dict = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) UpperCamelCase :Dict = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) UpperCamelCase :Any = emba.weight[:3, :5] tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[Any] =1E-4 def UpperCAmelCase ( self ) -> List[str]: # 2,12,16,64 UpperCamelCase :List[Any] = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) UpperCamelCase :int = embed_positions([2, 16, 768] )[None, None, :, :] UpperCamelCase , UpperCamelCase :List[str] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) UpperCamelCase :Optional[int] = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance )
259
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() __snake_case = logging.get_logger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Optional[Any] = SwinConfig( embed_dim=192 , depths=(2, 2, 18, 2) , num_heads=(6, 12, 24, 48) , window_size=12 , out_features=['''stage2''', '''stage3''', '''stage4'''] , ) UpperCamelCase :int = DetaConfig( backbone_config=SCREAMING_SNAKE_CASE__ , num_queries=900 , encoder_ffn_dim=2048 , decoder_ffn_dim=2048 , num_feature_levels=5 , assign_first_stage=SCREAMING_SNAKE_CASE__ , with_box_refine=SCREAMING_SNAKE_CASE__ , two_stage=SCREAMING_SNAKE_CASE__ , ) # set labels UpperCamelCase :str = '''huggingface/label-files''' if "o365" in model_name: UpperCamelCase :Dict = 366 UpperCamelCase :int = '''object365-id2label.json''' else: UpperCamelCase :str = 91 UpperCamelCase :Tuple = '''coco-detection-id2label.json''' UpperCamelCase :List[Any] = num_labels UpperCamelCase :Tuple = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) ) , '''r''' ) ) UpperCamelCase :Optional[int] = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCamelCase :List[Any] = idalabel UpperCamelCase :Optional[int] = {v: k for k, v in idalabel.items()} return config def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ): UpperCamelCase :Optional[int] = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.norm2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias''', F'''model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias''') ) if i < 3: rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.reduction.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.reduction.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.weight''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.weight''') ) rename_keys.append((F'''backbone.0.body.layers.{i}.downsample.norm.bias''', F'''model.backbone.model.encoder.layers.{i}.downsample.norm.bias''') ) rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') ) rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') ) rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') ) rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') ) rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') ) rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias''', F'''model.encoder.layers.{i}.self_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.weight''', F'''model.encoder.layers.{i}.self_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.attention_weights.bias''', F'''model.encoder.layers.{i}.self_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.weight''', F'''model.encoder.layers.{i}.self_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.value_proj.bias''', F'''model.encoder.layers.{i}.self_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.weight''', F'''model.encoder.layers.{i}.self_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.self_attn.output_proj.bias''', F'''model.encoder.layers.{i}.self_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.weight''', F'''model.encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm1.bias''', F'''model.encoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''model.encoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''model.encoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''model.encoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''model.encoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.weight''', F'''model.encoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''model.encoder.layers.{i}.final_layer_norm.bias''') ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias''', F'''model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.weight''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.attention_weights.bias''', F'''model.decoder.layers.{i}.encoder_attn.attention_weights.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.value_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.value_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.weight''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.cross_attn.output_proj.bias''', F'''model.decoder.layers.{i}.encoder_attn.output_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.weight''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm1.bias''', F'''model.decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''model.decoder.layers.{i}.self_attn.out_proj.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''model.decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.weight''', F'''model.decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm2.bias''', F'''model.decoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''model.decoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''model.decoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''model.decoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''model.decoder.layers.{i}.fc2.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.weight''', F'''model.decoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''model.decoder.layers.{i}.final_layer_norm.bias''') ) # fmt: on return rename_keys def _A ( SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :str = dct.pop(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = val def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[str] ): UpperCamelCase :Optional[Any] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): UpperCamelCase :Union[str, Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) UpperCamelCase :Dict = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight''' ) UpperCamelCase :Tuple = state_dict.pop(F'''backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase :Optional[Any] = in_proj_weight[:dim, :] UpperCamelCase :List[str] = in_proj_bias[: dim] UpperCamelCase :str = in_proj_weight[ dim : dim * 2, : ] UpperCamelCase :Tuple = in_proj_bias[ dim : dim * 2 ] UpperCamelCase :List[Any] = in_proj_weight[ -dim :, : ] UpperCamelCase :Optional[int] = in_proj_bias[-dim :] # fmt: on def _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): # transformer decoder self-attention layers UpperCamelCase :Dict = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention UpperCamelCase :Any = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) UpperCamelCase :Dict = state_dict.pop(F'''transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict UpperCamelCase :Any = in_proj_weight[:hidden_size, :] UpperCamelCase :int = in_proj_bias[:hidden_size] UpperCamelCase :str = in_proj_weight[ hidden_size : hidden_size * 2, : ] UpperCamelCase :Optional[Any] = in_proj_bias[hidden_size : hidden_size * 2] UpperCamelCase :List[Any] = in_proj_weight[-hidden_size:, :] UpperCamelCase :Any = in_proj_bias[-hidden_size:] def _A ( ): UpperCamelCase :Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCamelCase :List[Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): UpperCamelCase :Optional[Any] = get_deta_config(SCREAMING_SNAKE_CASE__ ) # load original state dict if model_name == "deta-swin-large": UpperCamelCase :str = hf_hub_download(repo_id='''nielsr/deta-checkpoints''' , filename='''adet_swin_ft.pth''' ) elif model_name == "deta-swin-large-o365": UpperCamelCase :Dict = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''' , filename='''deta_swin_pt_o365.pth''' ) else: raise ValueError(F'''Model name {model_name} not supported''' ) UpperCamelCase :Optional[int] = torch.load(SCREAMING_SNAKE_CASE__ , map_location='''cpu''' )['''model'''] # original state dict for name, param in state_dict.items(): print(SCREAMING_SNAKE_CASE__ , param.shape ) # rename keys UpperCamelCase :List[str] = create_rename_keys(SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) read_in_swin_q_k_v(SCREAMING_SNAKE_CASE__ , config.backbone_config ) read_in_decoder_q_k_v(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: UpperCamelCase :List[str] = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = val if "input_proj" in key: UpperCamelCase :Any = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: UpperCamelCase :List[str] = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = val # finally, create HuggingFace model and load state dict UpperCamelCase :List[Any] = DetaForObjectDetection(SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.eval() UpperCamelCase :Any = '''cuda''' if torch.cuda.is_available() else '''cpu''' model.to(SCREAMING_SNAKE_CASE__ ) # load image processor UpperCamelCase :Any = DetaImageProcessor(format='''coco_detection''' ) # verify our conversion on image UpperCamelCase :List[str] = prepare_img() UpperCamelCase :Any = processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ) UpperCamelCase :List[str] = encoding['''pixel_values'''] UpperCamelCase :List[Any] = model(pixel_values.to(SCREAMING_SNAKE_CASE__ ) ) # verify logits print('''Logits:''' , outputs.logits[0, :3, :3] ) print('''Boxes:''' , outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": UpperCamelCase :Any = torch.tensor( [[-7.63_08, -2.84_85, -5.37_37], [-7.20_37, -4.55_05, -4.80_27], [-7.29_43, -4.26_11, -4.66_17]] ) UpperCamelCase :List[str] = torch.tensor([[0.49_87, 0.49_69, 0.99_99], [0.25_49, 0.54_98, 0.48_05], [0.54_98, 0.27_57, 0.05_69]] ) elif model_name == "deta-swin-large-o365": UpperCamelCase :int = torch.tensor( [[-8.01_22, -3.57_20, -4.97_17], [-8.15_47, -3.68_86, -4.63_89], [-7.66_10, -3.61_94, -5.01_34]] ) UpperCamelCase :Optional[Any] = torch.tensor([[0.25_23, 0.55_49, 0.48_81], [0.77_15, 0.41_49, 0.46_01], [0.55_03, 0.27_53, 0.05_75]] ) assert torch.allclose(outputs.logits[0, :3, :3] , expected_logits.to(SCREAMING_SNAKE_CASE__ ) , atol=1e-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3] , expected_boxes.to(SCREAMING_SNAKE_CASE__ ) , atol=1e-4 ) print('''Everything ok!''' ) if pytorch_dump_folder_path: # Save model and processor logger.info(F'''Saving PyTorch model and processor to {pytorch_dump_folder_path}...''' ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Push to hub if push_to_hub: print('''Pushing model and processor to hub...''' ) model.push_to_hub(F'''jozhang97/{model_name}''' ) processor.push_to_hub(F'''jozhang97/{model_name}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() parser.add_argument( """--model_name""", type=str, default="""deta-swin-large""", choices=["""deta-swin-large""", """deta-swin-large-o365"""], help="""Name of the model you'd like to convert.""", ) 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 or not to push the converted model to the 🤗 hub.""" ) __snake_case = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
259
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , 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_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :List[Any] = parent UpperCamelCase :List[str] = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Optional[Any] = patch_size UpperCamelCase :Optional[Any] = num_channels UpperCamelCase :Union[str, Any] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :List[Any] = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :Any = backbone_out_indices UpperCamelCase :int = num_attention_heads UpperCamelCase :Union[str, Any] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :Optional[int] = hidden_dropout_prob UpperCamelCase :int = attention_probs_dropout_prob UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :Any = backbone_featmap_shape UpperCamelCase :Optional[int] = scope UpperCamelCase :Optional[int] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Tuple = (image_size // patch_size) ** 2 UpperCamelCase :int = num_patches + 1 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :int = None if self.use_labels: UpperCamelCase :str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Any = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Tuple = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[int] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: UpperCamelCase :Tuple = self.num_labels UpperCamelCase :Any = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :int = self.num_labels UpperCamelCase :str = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :List[str] = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Optional[Any] =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : Union[str, Any] =False def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Tuple = [*signature.parameters.keys()] UpperCamelCase :Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :int = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Optional[int]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = False UpperCamelCase :Dict = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Tuple = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :List[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Dict: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Tuple = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :List[str] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Tuple = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Tuple: pass @slow def UpperCAmelCase ( self ) -> Any: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :int = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> str: UpperCamelCase :Any = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :int = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = prepare_img() UpperCamelCase :Union[str, Any] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :List[str] = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
259
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer __snake_case = logging.get_logger(__name__) __snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all MVP models at https://huggingface.co/models?filter=mvp __snake_case = { """vocab_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json""", }, """added_tokens.json""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json""", }, """merges_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt""", }, """tokenizer_file""": { """RUCAIBox/mvp""": """https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json""", }, } __snake_case = { """RUCAIBox/mvp""": 10_24, } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : List[str] =VOCAB_FILES_NAMES UpperCamelCase_ : Any =PRETRAINED_VOCAB_FILES_MAP UpperCamelCase_ : Optional[int] =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCamelCase_ : List[Any] =['input_ids', 'attention_mask'] UpperCamelCase_ : int =MvpTokenizer def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="replace" , 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_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , tokenizer_file=SCREAMING_SNAKE_CASE_ , errors=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_ , add_prefix_space=SCREAMING_SNAKE_CASE_ , trim_offsets=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('''add_prefix_space''' , SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCamelCase :str = getattr(SCREAMING_SNAKE_CASE_ , pre_tok_state.pop('''type''' ) ) UpperCamelCase :str = add_prefix_space UpperCamelCase :Optional[int] = pre_tok_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCamelCase :int = '''post_processor''' UpperCamelCase :Tuple = getattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if tokenizer_component_instance: UpperCamelCase :Optional[Any] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: UpperCamelCase :Union[str, Any] = tuple(state['''sep'''] ) if "cls" in state: UpperCamelCase :int = tuple(state['''cls'''] ) UpperCamelCase :Optional[int] = False if state.get('''add_prefix_space''' , SCREAMING_SNAKE_CASE_ ) != add_prefix_space: UpperCamelCase :Tuple = add_prefix_space UpperCamelCase :Any = True if state.get('''trim_offsets''' , SCREAMING_SNAKE_CASE_ ) != trim_offsets: UpperCamelCase :Optional[int] = trim_offsets UpperCamelCase :str = True if changes_to_apply: UpperCamelCase :Optional[Any] = getattr(SCREAMING_SNAKE_CASE_ , state.pop('''type''' ) ) UpperCamelCase :List[Any] = component_class(**SCREAMING_SNAKE_CASE_ ) setattr(self.backend_tokenizer , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase ( self ) -> str: if self._mask_token is None: if self.verbose: logger.error('''Using mask_token, but it is not set yet.''' ) return None return str(self._mask_token ) @mask_token.setter def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: UpperCamelCase :Optional[Any] = AddedToken(SCREAMING_SNAKE_CASE_ , lstrip=SCREAMING_SNAKE_CASE_ , rstrip=SCREAMING_SNAKE_CASE_ ) if isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) else value UpperCamelCase :List[Any] = value def UpperCAmelCase ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: UpperCamelCase :Tuple = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._batch_encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , *SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> BatchEncoding: UpperCamelCase :int = kwargs.get('''is_split_into_words''' , SCREAMING_SNAKE_CASE_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True ''' '''to use it with pretokenized inputs.''' ) return super()._encode_plus(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: UpperCamelCase :Any = self._tokenizer.model.save(SCREAMING_SNAKE_CASE_ , name=SCREAMING_SNAKE_CASE_ ) return tuple(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None ) -> Dict: UpperCamelCase :Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> List[int]: UpperCamelCase :Union[str, Any] = [self.sep_token_id] UpperCamelCase :str = [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]
259
def _A ( ): for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def _A ( SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Optional[int] = 1 UpperCamelCase :List[Any] = 2 while i * i <= n: UpperCamelCase :str = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def _A ( ): return next(i for i in triangle_number_generator() if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500 ) if __name__ == "__main__": print(solution())
259
1
__snake_case = 8.3_1_4_4_5_9_8 def _A ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): if temperature < 0: raise Exception('''Temperature cannot be less than 0 K''' ) if molar_mass <= 0: raise Exception('''Molar mass cannot be less than or equal to 0 kg/mol''' ) else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example __snake_case = 3_00 __snake_case = 28 __snake_case = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
259
def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ): # Return True if there is node that has not iterated. UpperCamelCase :Tuple = [False] * len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = [] queue.append(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = True while queue: UpperCamelCase :Optional[Any] = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = True UpperCamelCase :Optional[int] = u return visited[t] def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str ): # This array is filled by BFS and to store path UpperCamelCase :Optional[int] = [-1] * (len(SCREAMING_SNAKE_CASE__ )) UpperCamelCase :Optional[int] = 0 while bfs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Dict = float('''Inf''' ) UpperCamelCase :str = sink while s != source: # Find the minimum value in select path UpperCamelCase :Optional[Any] = min(SCREAMING_SNAKE_CASE__ , graph[parent[s]][s] ) UpperCamelCase :Any = parent[s] max_flow += path_flow UpperCamelCase :Tuple = sink while v != source: UpperCamelCase :List[str] = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow UpperCamelCase :Any = parent[v] return max_flow __snake_case = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] __snake_case , __snake_case = 0, 5 print(ford_fulkerson(graph, source, sink))
259
1
import argparse import gc import json import os import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __snake_case = 16 __snake_case = 32 def _A ( SCREAMING_SNAKE_CASE__ : str ): return int(x / 2**20 ) class UpperCAmelCase_ : """simple docstring""" def __enter__( self ) -> List[Any]: gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero UpperCamelCase :List[str] = torch.cuda.memory_allocated() return self def __exit__( self , *SCREAMING_SNAKE_CASE_ ) -> Any: gc.collect() torch.cuda.empty_cache() UpperCamelCase :Dict = torch.cuda.memory_allocated() UpperCamelCase :Union[str, Any] = torch.cuda.max_memory_allocated() UpperCamelCase :Union[str, Any] = bamb(self.end - self.begin ) UpperCamelCase :List[Any] = bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def _A ( SCREAMING_SNAKE_CASE__ : Accelerator , SCREAMING_SNAKE_CASE__ : int = 16 , SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" , SCREAMING_SNAKE_CASE__ : int = 320 , SCREAMING_SNAKE_CASE__ : int = 160 , ): UpperCamelCase :Optional[Any] = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = load_dataset( '''glue''' , '''mrpc''' , split={'''train''': F'''train[:{n_train}]''', '''validation''': F'''validation[:{n_val}]'''} ) def tokenize_function(SCREAMING_SNAKE_CASE__ : int ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase :Any = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase :List[Any] = datasets.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase :str = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : Optional[int] ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. UpperCamelCase :Dict = DataLoader( tokenized_datasets['''train'''] , shuffle=SCREAMING_SNAKE_CASE__ , collate_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = DataLoader( tokenized_datasets['''validation'''] , shuffle=SCREAMING_SNAKE_CASE__ , collate_fn=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ): # Initialize accelerator UpperCamelCase :List[Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase :str = config['''lr'''] UpperCamelCase :Any = int(config['''num_epochs'''] ) UpperCamelCase :List[str] = int(config['''seed'''] ) UpperCamelCase :Any = int(config['''batch_size'''] ) UpperCamelCase :Optional[Any] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCamelCase , UpperCamelCase :Dict = get_dataloaders(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , args.n_train , args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase :Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCamelCase :List[Any] = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase :Tuple = optimizer_cls(params=model.parameters() , lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase :List[str] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCamelCase :Optional[Any] = 1 UpperCamelCase :Optional[int] = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase :Union[str, Any] = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__ , num_warmup_steps=0 , num_training_steps=SCREAMING_SNAKE_CASE__ , ) else: UpperCamelCase :Any = DummyScheduler(SCREAMING_SNAKE_CASE__ , total_num_steps=SCREAMING_SNAKE_CASE__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Any = accelerator.prepare( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCamelCase :Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase :Dict = 0 # Now we train the model UpperCamelCase :List[Any] = {} for epoch in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = model(**SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = outputs.loss UpperCamelCase :List[str] = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage accelerator.print('''Memory before entering the train : {}'''.format(bamb(tracemalloc.begin ) ) ) accelerator.print('''Memory consumed at the end of the train (end-begin): {}'''.format(tracemalloc.used ) ) accelerator.print('''Peak Memory consumed during the train (max-begin): {}'''.format(tracemalloc.peaked ) ) accelerator.print( '''Total Peak Memory consumed during the train (max): {}'''.format( tracemalloc.peaked + bamb(tracemalloc.begin ) ) ) UpperCamelCase :Optional[Any] = tracemalloc.peaked + bamb(tracemalloc.begin ) if args.peak_memory_upper_bound is not None: assert ( train_total_peak_memory[F'''epoch-{epoch}'''] <= args.peak_memory_upper_bound ), "Peak memory usage exceeded the upper bound" accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , '''peak_memory_utilization.json''' ) , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=SCREAMING_SNAKE_CASE__ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=SCREAMING_SNAKE_CASE__ , ) parser.add_argument( '''--output_dir''' , type=SCREAMING_SNAKE_CASE__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--peak_memory_upper_bound''' , type=SCREAMING_SNAKE_CASE__ , default=SCREAMING_SNAKE_CASE__ , help='''The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.''' , ) parser.add_argument( '''--n_train''' , type=SCREAMING_SNAKE_CASE__ , default=320 , help='''Number of training examples to use.''' , ) parser.add_argument( '''--n_val''' , type=SCREAMING_SNAKE_CASE__ , default=160 , help='''Number of validation examples to use.''' , ) parser.add_argument( '''--num_epochs''' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='''Number of train epochs.''' , ) UpperCamelCase :Union[str, Any] = parser.parse_args() UpperCamelCase :List[str] = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
259
from __future__ import annotations from typing import Any def _A ( SCREAMING_SNAKE_CASE__ : list[Any] ): create_state_space_tree(SCREAMING_SNAKE_CASE__ , [] , 0 ) def _A ( SCREAMING_SNAKE_CASE__ : list[Any] , SCREAMING_SNAKE_CASE__ : list[Any] , SCREAMING_SNAKE_CASE__ : int ): if index == len(SCREAMING_SNAKE_CASE__ ): print(SCREAMING_SNAKE_CASE__ ) return create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": __snake_case = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["""A""", """B""", """C"""]) generate_all_subsequences(seq)
259
1
import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class UpperCAmelCase_ ( lowercase ): """simple docstring""" # to overwrite at feature extractactor specific tests UpperCamelCase_ : int =None UpperCamelCase_ : Dict =None @property def UpperCAmelCase ( self ) -> Tuple: return self.feat_extract_tester.prepare_feat_extract_dict() def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''feature_size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''sampling_rate''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''padding_value''' ) ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :int = self.feat_extract_tester.prepare_inputs_for_common() UpperCamelCase :Dict = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :Optional[Any] = feat_extract.model_input_names[0] UpperCamelCase :Dict = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) for x, y in zip(SCREAMING_SNAKE_CASE_ , processed_features[input_name] ) ) ) UpperCamelCase :int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = BatchFeature({input_name: speech_inputs} , tensor_type='''np''' ) UpperCamelCase :Tuple = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase :str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def UpperCAmelCase ( self ) -> str: UpperCamelCase :List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :Tuple = feat_extract.model_input_names[0] UpperCamelCase :List[Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''pt''' ) UpperCamelCase :Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase :Tuple = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :Tuple = feat_extract.model_input_names[0] UpperCamelCase :Union[str, Any] = BatchFeature({input_name: speech_inputs} , tensor_type='''tf''' ) UpperCamelCase :List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: UpperCamelCase :Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_=False ) -> int: def _inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :Optional[int] = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE_ ) != length: return False return True def _inputs_are_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE_ ) , np.asarray(SCREAMING_SNAKE_CASE_ ) , atol=1e-3 ): return False return True UpperCamelCase :Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :int = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = feat_extract.model_input_names[0] UpperCamelCase :Any = BatchFeature({input_name: speech_inputs} ) UpperCamelCase :Tuple = self.feat_extract_tester.seq_length_diff UpperCamelCase :Tuple = self.feat_extract_tester.max_seq_length + pad_diff UpperCamelCase :Dict = self.feat_extract_tester.min_seq_length UpperCamelCase :Optional[Any] = self.feat_extract_tester.batch_size UpperCamelCase :List[str] = self.feat_extract_tester.feature_size # test padding for List[int] + numpy UpperCamelCase :List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = input_a[input_name] UpperCamelCase :Tuple = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' ) UpperCamelCase :int = input_a[input_name] UpperCamelCase :Any = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[-1] ) ) UpperCamelCase :str = input_a[input_name] UpperCamelCase :Any = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''np''' ) UpperCamelCase :List[Any] = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''max_length''' )[input_name] UpperCamelCase :Union[str, Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) UpperCamelCase :Dict = input_a[input_name] self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy UpperCamelCase :List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , pad_to_multiple_of=10 ) UpperCamelCase :Optional[Any] = input_a[input_name] UpperCamelCase :List[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , pad_to_multiple_of=10 ) UpperCamelCase :Dict = input_a[input_name] UpperCamelCase :str = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , pad_to_multiple_of=10 , max_length=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = input_a[input_name] UpperCamelCase :Any = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , pad_to_multiple_of=10 , max_length=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' , ) UpperCamelCase :List[str] = input_a[input_name] self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :int = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct UpperCamelCase :List[Any] = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1e-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1e-3 ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_=False ) -> Dict: def _inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :List[str] = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE_ ) != length: return False return True def _inputs_are_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE_ ) , np.asarray(SCREAMING_SNAKE_CASE_ ) , atol=1e-3 ): return False return True UpperCamelCase :Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = feat_extract.model_input_names[0] UpperCamelCase :Any = BatchFeature({input_name: speech_inputs} ) # truncate to smallest UpperCamelCase :int = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) , truncation=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = input_a[input_name] UpperCamelCase :Optional[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) ) UpperCamelCase :List[str] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) # truncate to smallest with np UpperCamelCase :Dict = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' , truncation=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Any = input_a[input_name] UpperCamelCase :List[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) , return_tensors='''np''' ) UpperCamelCase :List[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) # truncate to middle UpperCamelCase :str = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' , ) UpperCamelCase :int = input_a[input_name] UpperCamelCase :Tuple = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[1] ) , truncation=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = input_a[input_name] UpperCamelCase :Any = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[1] ) , return_tensors='''np''' ) UpperCamelCase :Any = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , truncation=SCREAMING_SNAKE_CASE_ )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , truncation=SCREAMING_SNAKE_CASE_ )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''max_length''' , truncation=SCREAMING_SNAKE_CASE_ )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy UpperCamelCase :Any = 12 UpperCamelCase :Tuple = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Tuple = input_a[input_name] UpperCamelCase :List[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Optional[int] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of UpperCamelCase :int = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: UpperCamelCase :Any = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Optional[int]: self._check_padding(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: self._check_padding(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: self._check_truncation(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: self._check_truncation(numpify=SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :Tuple = self.feat_extract_tester.prepare_inputs_for_common() UpperCamelCase :Optional[int] = feat_extract.model_input_names[0] UpperCamelCase :int = BatchFeature({input_name: speech_inputs} ) UpperCamelCase :List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''np''' )[input_name] UpperCamelCase :str = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''pt''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) @require_tf def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) UpperCamelCase :int = self.feat_extract_tester.prepare_inputs_for_common() UpperCamelCase :Any = feat_extract.model_input_names[0] UpperCamelCase :Any = BatchFeature({input_name: speech_inputs} ) UpperCamelCase :Union[str, Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''np''' )[input_name] UpperCamelCase :Optional[int] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''tf''' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.feat_extract_dict UpperCamelCase :Dict = True UpperCamelCase :Optional[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = self.feat_extract_tester.prepare_inputs_for_common() UpperCamelCase :Dict = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase :List[str] = feat_extract.model_input_names[0] UpperCamelCase :int = BatchFeature({input_name: speech_inputs} ) UpperCamelCase :List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ , padding='''longest''' , return_tensors='''np''' ) self.assertIn('''attention_mask''' , SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Dict = self.feat_extract_dict UpperCamelCase :Tuple = True UpperCamelCase :List[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = self.feat_extract_tester.prepare_inputs_for_common() UpperCamelCase :Any = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] UpperCamelCase :Optional[int] = feat_extract.model_input_names[0] UpperCamelCase :Union[str, Any] = BatchFeature({input_name: speech_inputs} ) UpperCamelCase :Optional[Any] = min(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = feat_extract.pad( SCREAMING_SNAKE_CASE_ , padding='''max_length''' , max_length=SCREAMING_SNAKE_CASE_ , truncation=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) self.assertIn('''attention_mask''' , SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
259
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : List[Any] =['pixel_values'] def __init__( self , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = 1 / 255 , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = True , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = size if size is not None else {'''height''': 224, '''width''': 224} UpperCamelCase :Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) UpperCamelCase :Optional[int] = do_resize UpperCamelCase :int = do_rescale UpperCamelCase :Tuple = do_normalize UpperCamelCase :str = do_center_crop UpperCamelCase :int = crop_size UpperCamelCase :Tuple = size UpperCamelCase :List[str] = resample UpperCamelCase :Tuple = rescale_factor UpperCamelCase :Optional[Any] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN UpperCamelCase :Optional[int] = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "shortest_edge" in size: UpperCamelCase :str = get_resize_output_image_size(SCREAMING_SNAKE_CASE_ , size=size['''shortest_edge'''] , default_to_square=SCREAMING_SNAKE_CASE_ ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: UpperCamelCase :Optional[int] = (size['''height'''], size['''width''']) else: raise ValueError(F'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}''' ) 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: UpperCamelCase :Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(SCREAMING_SNAKE_CASE_ , size=(size['''height'''], size['''width''']) , data_format=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ ) -> np.ndarray: 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_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None , **SCREAMING_SNAKE_CASE_ , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ , data_format=SCREAMING_SNAKE_CASE_ , **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_ = None , SCREAMING_SNAKE_CASE_ = None , SCREAMING_SNAKE_CASE_ = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE_ , ) -> BatchFeature: UpperCamelCase :Union[str, Any] = do_resize if do_resize is not None else self.do_resize UpperCamelCase :Optional[int] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase :Optional[Any] = do_normalize if do_normalize is not None else self.do_normalize UpperCamelCase :Union[str, Any] = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase :Optional[int] = crop_size if crop_size is not None else self.crop_size UpperCamelCase :Dict = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = resample if resample is not None else self.resample UpperCamelCase :List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase :Optional[Any] = image_mean if image_mean is not None else self.image_mean UpperCamelCase :Dict = image_std if image_std is not None else self.image_std UpperCamelCase :Dict = size if size is not None else self.size UpperCamelCase :Optional[int] = get_size_dict(SCREAMING_SNAKE_CASE_ ) if not is_batched(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :str = [images] if not valid_images(SCREAMING_SNAKE_CASE_ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. UpperCamelCase :Tuple = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase :List[Any] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: UpperCamelCase :Tuple = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase :Union[str, Any] = [self.rescale(image=SCREAMING_SNAKE_CASE_ , scale=SCREAMING_SNAKE_CASE_ ) for image in images] if do_normalize: UpperCamelCase :Union[str, Any] = [self.normalize(image=SCREAMING_SNAKE_CASE_ , mean=SCREAMING_SNAKE_CASE_ , std=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :List[str] = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :int = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ )
259
1
from __future__ import annotations from collections.abc import Generator def _A ( ): UpperCamelCase :dict[int, int] = {} UpperCamelCase :List[str] = 2 while True: UpperCamelCase :Optional[Any] = factor_map.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if factor: UpperCamelCase :List[str] = factor + prime while x in factor_map: x += factor UpperCamelCase :int = factor else: UpperCamelCase :Any = prime yield prime prime += 1 def _A ( SCREAMING_SNAKE_CASE__ : float = 1e1_0 ): UpperCamelCase :Tuple = sieve() UpperCamelCase :str = 1 while True: UpperCamelCase :Dict = next(SCREAMING_SNAKE_CASE__ ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(SCREAMING_SNAKE_CASE__ ) n += 2 if __name__ == "__main__": print(solution())
259
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str]=() , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]="no" , SCREAMING_SNAKE_CASE__ : Dict="29500" ): UpperCamelCase :List[Any] = False UpperCamelCase :Tuple = False if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ): UpperCamelCase :Dict = True elif "IPython" in sys.modules: UpperCamelCase :int = '''google.colab''' in str(sys.modules['''IPython'''].get_ipython() ) try: UpperCamelCase :Any = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.''' ) if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME''' , SCREAMING_SNAKE_CASE__ ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside ''' '''your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if num_processes is None: UpperCamelCase :Tuple = 8 UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''TPU''' ) print(F'''Launching a training on {num_processes} TPU cores.''' ) xmp.spawn(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on one CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) else: if num_processes is None: raise ValueError( '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized ''' '''inside your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if torch.cuda.is_initialized(): raise ValueError( '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction ''' '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA ''' '''function.''' ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port=SCREAMING_SNAKE_CASE__ , mixed_precision=SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''MULTI_GPU''' ) print(F'''Launching training on {num_processes} GPUs.''' ) try: start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. ''' '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. ''' '''Please review your imports and test them when running the `notebook_launcher()` to identify ''' '''which one is problematic.''' ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): UpperCamelCase :Any = '''1''' print('''Launching training on MPS.''' ) elif torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple=() , SCREAMING_SNAKE_CASE__ : int=2 ): from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port='''29500''' , accelerate_mixed_precision='''no''' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='''yes''' , ): UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , debug=SCREAMING_SNAKE_CASE__ ) start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' )
259
1
import json import os import tempfile import transformers import datasets from utils import generate_example_dataset, get_duration __snake_case = 50_00_00 __snake_case , __snake_case = os.path.split(__file__) __snake_case = os.path.join(RESULTS_BASEPATH, """results""", RESULTS_FILENAME.replace(""".py""", """.json""")) @get_duration def _A ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , **SCREAMING_SNAKE_CASE__ : Tuple ): UpperCamelCase :str = dataset.map(**SCREAMING_SNAKE_CASE__ ) @get_duration def _A ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , **SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :List[str] = dataset.filter(**SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :str = {'''num examples''': SPEED_TEST_N_EXAMPLES} with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase :Dict = datasets.Features({'''text''': datasets.Value('''string''' ), '''numbers''': datasets.Value('''float32''' )} ) UpperCamelCase :int = generate_example_dataset( os.path.join(SCREAMING_SNAKE_CASE__ , '''dataset.arrow''' ) , SCREAMING_SNAKE_CASE__ , num_examples=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = transformers.AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=SCREAMING_SNAKE_CASE__ ) def tokenize(SCREAMING_SNAKE_CASE__ : Optional[int] ): return tokenizer(examples['''text'''] ) UpperCamelCase :List[Any] = map(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = map(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = map(SCREAMING_SNAKE_CASE__ , function=lambda SCREAMING_SNAKE_CASE__ : None , batched=SCREAMING_SNAKE_CASE__ ) with dataset.formatted_as(type='''numpy''' ): UpperCamelCase :Optional[int] = map(SCREAMING_SNAKE_CASE__ , function=lambda SCREAMING_SNAKE_CASE__ : None , batched=SCREAMING_SNAKE_CASE__ ) with dataset.formatted_as(type='''pandas''' ): UpperCamelCase :str = map(SCREAMING_SNAKE_CASE__ , function=lambda SCREAMING_SNAKE_CASE__ : None , batched=SCREAMING_SNAKE_CASE__ ) with dataset.formatted_as(type='''torch''' , columns='''numbers''' ): UpperCamelCase :Optional[int] = map(SCREAMING_SNAKE_CASE__ , function=lambda SCREAMING_SNAKE_CASE__ : None , batched=SCREAMING_SNAKE_CASE__ ) with dataset.formatted_as(type='''tensorflow''' , columns='''numbers''' ): UpperCamelCase :Union[str, Any] = map(SCREAMING_SNAKE_CASE__ , function=lambda SCREAMING_SNAKE_CASE__ : None , batched=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = map(SCREAMING_SNAKE_CASE__ , function=SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = filter(SCREAMING_SNAKE_CASE__ ) # Activate later when tokenizer support batched inputs # with dataset.formatted_as(type='numpy'): # times[func.__name__ + " fast-tokenizer batched numpy"] = func(dataset, function=tokenize, batched=True) with open(SCREAMING_SNAKE_CASE__ , '''wb''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ ).encode('''utf-8''' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_map_filter()
259
import sys def _A ( SCREAMING_SNAKE_CASE__ : List[str] ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] UpperCamelCase :List[Any] = [[0 for x in range(SCREAMING_SNAKE_CASE__ )] for x in range(SCREAMING_SNAKE_CASE__ )] for chain_length in range(2 , SCREAMING_SNAKE_CASE__ ): for a in range(1 , n - chain_length + 1 ): UpperCamelCase :Optional[Any] = a + chain_length - 1 UpperCamelCase :int = sys.maxsize for c in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Any = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: UpperCamelCase :int = cost UpperCamelCase :List[str] = c return matrix, sol def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ): if i == j: print('''A''' + str(SCREAMING_SNAKE_CASE__ ) , end=''' ''' ) else: print('''(''' , end=''' ''' ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , optimal_solution[i][j] + 1 , SCREAMING_SNAKE_CASE__ ) print(''')''' , end=''' ''' ) def _A ( ): UpperCamelCase :Optional[int] = [30, 35, 15, 5, 10, 20, 25] UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 UpperCamelCase , UpperCamelCase :Dict = matrix_chain_order(SCREAMING_SNAKE_CASE__ ) print('''No. of Operation required: ''' + str(matrix[1][n - 1] ) ) print_optiomal_solution(SCREAMING_SNAKE_CASE__ , 1 , n - 1 ) if __name__ == "__main__": main()
259
1
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/config.json""", """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Tuple ='xlnet' UpperCamelCase_ : List[Any] =['mems'] UpperCamelCase_ : int ={ 'n_token': 'vocab_size', # Backward compatibility 'hidden_size': 'd_model', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , SCREAMING_SNAKE_CASE_=3_2000 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=24 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=4096 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="bi" , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=-1 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="last" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="tanh" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , **SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: UpperCamelCase :Optional[Any] = vocab_size UpperCamelCase :List[Any] = d_model UpperCamelCase :int = n_layer UpperCamelCase :int = n_head if d_model % n_head != 0: raise ValueError(F'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0''' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'''`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})''' ) UpperCamelCase :str = d_model // n_head UpperCamelCase :Union[str, Any] = ff_activation UpperCamelCase :Optional[int] = d_inner UpperCamelCase :Tuple = untie_r UpperCamelCase :Dict = attn_type UpperCamelCase :int = initializer_range UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :Union[str, Any] = dropout UpperCamelCase :Optional[Any] = mem_len UpperCamelCase :Tuple = reuse_len UpperCamelCase :List[str] = bi_data UpperCamelCase :Dict = clamp_len UpperCamelCase :List[str] = same_length UpperCamelCase :Any = summary_type UpperCamelCase :Tuple = summary_use_proj UpperCamelCase :Dict = summary_activation UpperCamelCase :Dict = summary_last_dropout UpperCamelCase :List[str] = start_n_top UpperCamelCase :Optional[int] = end_n_top UpperCamelCase :str = bos_token_id UpperCamelCase :Tuple = pad_token_id UpperCamelCase :Tuple = eos_token_id if "use_cache" in kwargs: warnings.warn( '''The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`''' ''' instead.''' , SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :List[str] = kwargs['''use_cache'''] UpperCamelCase :Optional[Any] = use_mems_eval UpperCamelCase :Tuple = use_mems_train super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) @property def UpperCAmelCase ( self ) -> Dict: logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Any: # Message copied from Transformer-XL documentation raise NotImplementedError( F'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
259
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() __snake_case = logging.get_logger(__name__) __snake_case = """https://openaipublic.azureedge.net/jukebox/models/""" __snake_case = { """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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] ): if key.endswith('''.model.1.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :int = key.replace('''.model.1.bias''' , '''.conv1d_1.bias''' ) elif key.endswith('''.model.1.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Union[str, Any] = key.replace('''.model.1.weight''' , '''.conv1d_1.weight''' ) elif key.endswith('''.model.3.bias''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[Any] = key.replace('''.model.3.bias''' , '''.conv1d_2.bias''' ) elif key.endswith('''.model.3.weight''' ) and len(key.split('''.''' ) ) > 10: UpperCamelCase :Optional[int] = key.replace('''.model.3.weight''' , '''.conv1d_2.weight''' ) if "conditioner_blocks.0." in key: UpperCamelCase :Any = key.replace('''conditioner_blocks.0''' , '''conditioner_blocks''' ) if "prime_prior" in key: UpperCamelCase :int = 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 :Any = 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 :str = 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 _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Optional[int] = {} import re UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :str = re.compile( R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :int = re.compile(R'''encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[int] = re.compile(R'''decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Optional[Any] = re.compile(R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)''' ) UpperCamelCase :int = re.compile( R'''conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)''' ) UpperCamelCase :Tuple = 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(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_encoder_block_conv_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :List[Any] = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_encoder_block_conv_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_encoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = regex_match.groups() UpperCamelCase :Any = int(groups[2] ) * 2 + int(groups[3] ) UpperCamelCase :Any = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :str = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.''' UpperCamelCase :List[str] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = prefix + resnet_block UpperCamelCase :str = re_encoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_encoder_block_proj_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_encoder_block_proj_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = regex_match.groups() UpperCamelCase :int = F'''encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}''' UpperCamelCase :str = re_encoder_block_proj_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :Union[str, Any] = re_decoder_block_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_decoder_block_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :List[str] = int(groups[2] ) * 2 + int(groups[3] ) - 2 UpperCamelCase :Optional[int] = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Any = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.''' UpperCamelCase :Optional[int] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Optional[int] = re_decoder_block_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_decoder_block_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = re_decoder_block_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = regex_match.groups() UpperCamelCase :List[Any] = F'''decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_decoder_block_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = re_prior_cond_conv_out.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = regex_match.groups() UpperCamelCase :str = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}''' UpperCamelCase :int = re_prior_cond_conv_out.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_resnet.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = re_prior_cond_resnet.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = regex_match.groups() UpperCamelCase :Optional[Any] = int(groups[1] ) * 2 + int(groups[2] ) - 2 UpperCamelCase :int = {'''1''': 1, '''3''': 2}[groups[-2]] UpperCamelCase :Tuple = F'''conditioner_blocks.upsampler.upsample_block.{block_index}.''' UpperCamelCase :List[Any] = F'''resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}''' UpperCamelCase :Any = prefix + resnet_block UpperCamelCase :Dict = re_prior_cond_resnet.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif re_prior_cond_proj_in.fullmatch(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[str] = re_prior_cond_proj_in.match(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = regex_match.groups() UpperCamelCase :Dict = F'''conditioner_blocks.upsampler.proj_in.{groups[-1]}''' UpperCamelCase :Any = re_prior_cond_proj_in.sub(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # keep original key else: UpperCamelCase :List[str] = original_key UpperCamelCase :Any = replace_key(SCREAMING_SNAKE_CASE__ ) 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 :Union[str, Any] = model_state_dict[F'''{key_prefix}.{key}'''] print(F'''{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match''' ) UpperCamelCase :List[Any] = original_key UpperCamelCase :Any = original_key UpperCamelCase :Optional[int] = value return new_dict @torch.no_grad() def _A ( SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Dict=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' ): UpperCamelCase :Dict = requests.get(F'''{PREFIX}{file}''' , allow_redirects=SCREAMING_SNAKE_CASE__ ) os.makedirs(F'''{pytorch_dump_folder_path}/''' , exist_ok=SCREAMING_SNAKE_CASE__ ) open(F'''{pytorch_dump_folder_path}/{file.split("/" )[-1]}''' , '''wb''' ).write(r.content ) UpperCamelCase :Optional[int] = MODEL_MAPPING[model_name.split('''/''' )[-1]] UpperCamelCase :Any = JukeboxConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = JukeboxModel(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = [] UpperCamelCase :List[Any] = {} for i, dict_name in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :int = torch.load(F'''{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}''' )['''model'''] UpperCamelCase :Tuple = {} for k in old_dic.keys(): if k.endswith('''.b''' ): UpperCamelCase :Optional[int] = old_dic[k] elif k.endswith('''.w''' ): UpperCamelCase :Optional[Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: UpperCamelCase :Optional[Any] = old_dic[k] else: UpperCamelCase :Any = old_dic[k] UpperCamelCase :Any = '''vqvae''' if i == 0 else F'''priors.{3 - i}''' UpperCamelCase :Dict = fix_jukebox_keys(SCREAMING_SNAKE_CASE__ , model.state_dict() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) weight_dict.append(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = weight_dict.pop(0 ) model.vqvae.load_state_dict(SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) with open(F'''{pytorch_dump_folder_path}/mapping.json''' , '''w''' ) as txtfile: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(F'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) return weight_dict if __name__ == "__main__": __snake_case = 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.""", ) __snake_case = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
259
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """junnyu/roformer_chinese_small""": """https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json""", """junnyu/roformer_chinese_base""": """https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json""", """junnyu/roformer_chinese_char_small""": ( """https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json""" ), """junnyu/roformer_chinese_char_base""": ( """https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json""" ), """junnyu/roformer_small_discriminator""": ( """https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json""" ), """junnyu/roformer_small_generator""": ( """https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json""" ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : int ='roformer' def __init__( self , SCREAMING_SNAKE_CASE_=5_0000 , SCREAMING_SNAKE_CASE_=None , 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_=1536 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = vocab_size UpperCamelCase :List[Any] = hidden_size if embedding_size is None else embedding_size UpperCamelCase :str = hidden_size UpperCamelCase :Dict = num_hidden_layers UpperCamelCase :Union[str, Any] = num_attention_heads UpperCamelCase :Optional[int] = hidden_act UpperCamelCase :Tuple = intermediate_size UpperCamelCase :Union[str, Any] = hidden_dropout_prob UpperCamelCase :Union[str, Any] = attention_probs_dropout_prob UpperCamelCase :Dict = max_position_embeddings UpperCamelCase :Optional[int] = type_vocab_size UpperCamelCase :str = initializer_range UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Any = rotary_value UpperCamelCase :Optional[int] = use_cache class UpperCAmelCase_ ( lowercase ): """simple docstring""" @property def UpperCAmelCase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": UpperCamelCase :Union[str, Any] = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCamelCase :Dict = {0: '''batch''', 1: '''sequence'''} UpperCamelCase :List[str] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
259
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_torch, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_torch_available, is_vision_available if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import MgpstrProcessor, ViTImageProcessor @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Union[str, Any] =ViTImageProcessor if is_vision_available() else None @property def UpperCAmelCase ( self ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def UpperCAmelCase ( self ) -> int: UpperCamelCase :Union[str, Any] = (3, 32, 128) UpperCamelCase :Any = tempfile.mkdtemp() # fmt: off UpperCamelCase :int = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on UpperCamelCase :Optional[int] = dict(zip(SCREAMING_SNAKE_CASE_ , range(len(SCREAMING_SNAKE_CASE_ ) ) ) ) UpperCamelCase :Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(SCREAMING_SNAKE_CASE_ ) + '''\n''' ) UpperCamelCase :Tuple = { '''do_normalize''': False, '''do_resize''': True, '''image_processor_type''': '''ViTImageProcessor''', '''resample''': 3, '''size''': {'''height''': 32, '''width''': 128}, } UpperCamelCase :str = os.path.join(self.tmpdirname , SCREAMING_SNAKE_CASE_ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> int: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , **SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: return ViTImageProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: shutil.rmtree(self.tmpdirname ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta ) UpperCamelCase :List[Any] = Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE_ , 0 , -1 ) ) return image_input def UpperCAmelCase ( self ) -> str: UpperCamelCase :str = self.get_tokenizer() UpperCamelCase :Union[str, Any] = self.get_image_processor() UpperCamelCase :List[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Dict = MgpstrProcessor.from_pretrained(self.tmpdirname , use_fast=SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.char_tokenizer , SCREAMING_SNAKE_CASE_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[int] = self.get_tokenizer() UpperCamelCase :Dict = self.get_image_processor() UpperCamelCase :List[Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase :Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) UpperCamelCase :Optional[Any] = self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) UpperCamelCase :int = MgpstrProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=SCREAMING_SNAKE_CASE_ , padding_value=1.0 ) self.assertEqual(processor.char_tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.char_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 ) -> Union[str, Any]: UpperCamelCase :Tuple = self.get_image_processor() UpperCamelCase :List[str] = self.get_tokenizer() UpperCamelCase :str = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = self.prepare_image_inputs() UpperCamelCase :List[str] = image_processor(SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) UpperCamelCase :Optional[Any] = processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def UpperCAmelCase ( self ) -> Any: UpperCamelCase :Optional[Any] = self.get_image_processor() UpperCamelCase :Union[str, Any] = self.get_tokenizer() UpperCamelCase :int = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = '''test''' UpperCamelCase :Optional[int] = processor(text=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = tokenizer(SCREAMING_SNAKE_CASE_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :List[str] = self.get_image_processor() UpperCamelCase :Tuple = self.get_tokenizer() UpperCamelCase :Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = '''test''' UpperCamelCase :str = self.prepare_image_inputs() UpperCamelCase :Dict = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''labels'''] ) # test if it raises when no input is passed with pytest.raises(SCREAMING_SNAKE_CASE_ ): processor() def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Optional[Any] = self.get_image_processor() UpperCamelCase :Any = self.get_tokenizer() UpperCamelCase :Union[str, Any] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase :Union[str, Any] = processor.char_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = tokenizer.batch_decode(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = [seq.replace(''' ''' , '''''' ) for seq in decoded_tok] self.assertListEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :List[Any] = self.get_image_processor() UpperCamelCase :Optional[Any] = self.get_tokenizer() UpperCamelCase :Any = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = None UpperCamelCase :List[Any] = self.prepare_image_inputs() UpperCamelCase :Union[str, Any] = processor(text=SCREAMING_SNAKE_CASE_ , images=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :str = self.get_image_processor() UpperCamelCase :Tuple = self.get_tokenizer() UpperCamelCase :Optional[int] = MgpstrProcessor(tokenizer=SCREAMING_SNAKE_CASE_ , image_processor=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.randn(1 , 27 , 38 ) UpperCamelCase :Union[str, Any] = torch.randn(1 , 27 , 5_0257 ) UpperCamelCase :Optional[Any] = torch.randn(1 , 27 , 3_0522 ) UpperCamelCase :Optional[Any] = processor.batch_decode([char_input, bpe_input, wp_input] ) self.assertListEqual(list(results.keys() ) , ['''generated_text''', '''scores''', '''char_preds''', '''bpe_preds''', '''wp_preds'''] )
259
1
from pathlib import Path import fire def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ): UpperCamelCase :Dict = Path(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = Path(SCREAMING_SNAKE_CASE__ ) dest_dir.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) for path in src_dir.iterdir(): UpperCamelCase :Tuple = [x.rstrip() for x in list(path.open().readlines() )][:n] UpperCamelCase :int = dest_dir.joinpath(path.name ) print(SCREAMING_SNAKE_CASE__ ) dest_path.open('''w''' ).write('''\n'''.join(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": fire.Fire(minify)
259
import math def _A ( SCREAMING_SNAKE_CASE__ : int = 100 ): UpperCamelCase :Dict = sum(i * i for i in range(1 , n + 1 ) ) UpperCamelCase :List[str] = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
259
1
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , 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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> Dict: UpperCamelCase :Any = parent UpperCamelCase :Dict = 13 UpperCamelCase :List[Any] = 7 UpperCamelCase :List[Any] = True UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = True UpperCamelCase :List[str] = True UpperCamelCase :Dict = 99 UpperCamelCase :Any = 32 UpperCamelCase :Tuple = 2 UpperCamelCase :Union[str, Any] = 4 UpperCamelCase :List[str] = 37 UpperCamelCase :Dict = '''gelu''' UpperCamelCase :Dict = 0.1 UpperCamelCase :Tuple = 0.1 UpperCamelCase :Dict = 512 UpperCamelCase :str = 16 UpperCamelCase :Optional[Any] = 2 UpperCamelCase :Dict = 0.02 UpperCamelCase :Optional[int] = 3 UpperCamelCase :int = 4 UpperCamelCase :Dict = None def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Optional[int] = None if self.use_input_mask: UpperCamelCase :Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Dict = None if self.use_token_type_ids: UpperCamelCase :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Union[str, Any] = None UpperCamelCase :Optional[int] = None UpperCamelCase :Any = None if self.use_labels: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=SCREAMING_SNAKE_CASE_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_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_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = TFRoFormerModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} UpperCamelCase :int = [input_ids, input_mask] UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.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_ ) -> int: UpperCamelCase :List[Any] = True UpperCamelCase :Union[str, Any] = TFRoFormerForCausalLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Any = model(SCREAMING_SNAKE_CASE_ )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_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_ ) -> Union[str, Any]: UpperCamelCase :str = TFRoFormerForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_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_ ) -> List[str]: UpperCamelCase :List[Any] = self.num_labels UpperCamelCase :int = TFRoFormerForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Optional[Any] = model(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_ ) -> int: UpperCamelCase :List[Any] = self.num_choices UpperCamelCase :Any = TFRoFormerForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :int = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :Any = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :List[Any] = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) 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: UpperCamelCase :Union[str, Any] = self.num_labels UpperCamelCase :Dict = TFRoFormerForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.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_ ) -> Union[str, Any]: UpperCamelCase :Union[str, Any] = TFRoFormerForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(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 ) -> Tuple: UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : str =( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) UpperCamelCase_ : Tuple =( { 'feature-extraction': TFRoFormerModel, 'fill-mask': TFRoFormerForMaskedLM, 'question-answering': TFRoFormerForQuestionAnswering, 'text-classification': TFRoFormerForSequenceClassification, 'text-generation': TFRoFormerForCausalLM, 'token-classification': TFRoFormerForTokenClassification, 'zero-shot': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : Optional[Any] =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = TFRoFormerModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> List[str]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Tuple = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) UpperCamelCase :Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase :str = model(SCREAMING_SNAKE_CASE_ )[0] # TODO Replace vocab size UpperCamelCase :Tuple = 5_0000 UpperCamelCase :Optional[Any] = [1, 6, vocab_size] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. UpperCamelCase :int = tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =1E-4 def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :str = tf.constant([[4, 10]] ) UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) UpperCamelCase :str = emba(input_ids.shape ) UpperCamelCase :List[str] = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Dict = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) UpperCamelCase :Dict = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) UpperCamelCase :Any = emba.weight[:3, :5] tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[Any] =1E-4 def UpperCAmelCase ( self ) -> List[str]: # 2,12,16,64 UpperCamelCase :List[Any] = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) UpperCamelCase :int = embed_positions([2, 16, 768] )[None, None, :, :] UpperCamelCase , UpperCamelCase :List[str] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) UpperCamelCase :Optional[int] = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance )
259
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase :List[str] = True for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase :List[Any] = True if a[i].islower(): UpperCamelCase :List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
259
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case = { """configuration_mobilebert""": [ """MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MobileBertConfig""", """MobileBertOnnxConfig""", ], """tokenization_mobilebert""": ["""MobileBertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["""MobileBertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """MobileBertForMaskedLM""", """MobileBertForMultipleChoice""", """MobileBertForNextSentencePrediction""", """MobileBertForPreTraining""", """MobileBertForQuestionAnswering""", """MobileBertForSequenceClassification""", """MobileBertForTokenClassification""", """MobileBertLayer""", """MobileBertModel""", """MobileBertPreTrainedModel""", """load_tf_weights_in_mobilebert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ """TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFMobileBertForMaskedLM""", """TFMobileBertForMultipleChoice""", """TFMobileBertForNextSentencePrediction""", """TFMobileBertForPreTraining""", """TFMobileBertForQuestionAnswering""", """TFMobileBertForSequenceClassification""", """TFMobileBertForTokenClassification""", """TFMobileBertMainLayer""", """TFMobileBertModel""", """TFMobileBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
259
from math import factorial __snake_case = {str(digit): factorial(digit) for digit in range(10)} def _A ( SCREAMING_SNAKE_CASE__ : int ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Parameter number must be int''' ) if number < 0: raise ValueError('''Parameter number must be greater than or equal to 0''' ) # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(SCREAMING_SNAKE_CASE__ ) ) def _A ( SCREAMING_SNAKE_CASE__ : int = 60 , SCREAMING_SNAKE_CASE__ : int = 1000000 ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise TypeError('''Parameters chain_length and number_limit must be int''' ) if chain_length <= 0 or number_limit <= 0: raise ValueError( '''Parameters chain_length and number_limit must be greater than 0''' ) # the counter for the chains with the exact desired length UpperCamelCase :Any = 0 # the cached sizes of the previous chains UpperCamelCase :dict[int, int] = {} for start_chain_element in range(1 , SCREAMING_SNAKE_CASE__ ): # The temporary set will contain the elements of the chain UpperCamelCase :List[Any] = set() UpperCamelCase :Any = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. UpperCamelCase :Optional[Any] = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(SCREAMING_SNAKE_CASE__ ) chain_set_length += 1 UpperCamelCase :List[Any] = digit_factorial_sum(SCREAMING_SNAKE_CASE__ ) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] UpperCamelCase :Any = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(f'''{solution()}''')
259
1
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """BridgeTower/bridgetower-base""": """https://huggingface.co/BridgeTower/bridgetower-base/blob/main/config.json""", """BridgeTower/bridgetower-base-itm-mlm""": ( """https://huggingface.co/BridgeTower/bridgetower-base-itm-mlm/blob/main/config.json""" ), } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Any ='bridgetower_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=288 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , **SCREAMING_SNAKE_CASE_ , ) -> Optional[int]: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :List[Any] = num_channels UpperCamelCase :Union[str, Any] = patch_size UpperCamelCase :Any = image_size UpperCamelCase :Tuple = initializer_factor UpperCamelCase :int = layer_norm_eps UpperCamelCase :Tuple = stop_gradient UpperCamelCase :List[Any] = share_layernorm UpperCamelCase :Dict = remove_last_layer @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> "PretrainedConfig": UpperCamelCase , UpperCamelCase :str = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if config_dict.get('''model_type''' ) == "bridgetower": UpperCamelCase :Union[str, Any] = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : int ='bridgetower_text_model' def __init__( self , SCREAMING_SNAKE_CASE_=5_0265 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=514 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , **SCREAMING_SNAKE_CASE_ , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = vocab_size UpperCamelCase :Any = hidden_size UpperCamelCase :Any = num_hidden_layers UpperCamelCase :List[str] = num_attention_heads UpperCamelCase :int = hidden_act UpperCamelCase :Tuple = initializer_factor UpperCamelCase :List[Any] = intermediate_size UpperCamelCase :Any = hidden_dropout_prob UpperCamelCase :Any = attention_probs_dropout_prob UpperCamelCase :Optional[int] = max_position_embeddings UpperCamelCase :str = type_vocab_size UpperCamelCase :Optional[int] = layer_norm_eps UpperCamelCase :List[str] = position_embedding_type UpperCamelCase :Optional[Any] = use_cache UpperCamelCase :Optional[int] = pad_token_id UpperCamelCase :Tuple = bos_token_id UpperCamelCase :Optional[Any] = eos_token_id @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> "PretrainedConfig": UpperCamelCase , UpperCamelCase :List[Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if config_dict.get('''model_type''' ) == "bridgetower": UpperCamelCase :int = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : int ='bridgetower' def __init__( self , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=1e-05 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_="add" , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=6 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Optional[Any]: # TODO: remove this once the Hub files are updated. UpperCamelCase :int = kwargs.pop('''text_config_dict''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = kwargs.pop('''vision_config_dict''' , SCREAMING_SNAKE_CASE_ ) super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = share_cross_modal_transformer_layers UpperCamelCase :Dict = hidden_act UpperCamelCase :str = hidden_size UpperCamelCase :Any = initializer_factor UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :List[str] = share_link_tower_layers UpperCamelCase :List[Any] = link_tower_type UpperCamelCase :Any = num_attention_heads UpperCamelCase :Union[str, Any] = num_hidden_layers UpperCamelCase :Union[str, Any] = tie_word_embeddings UpperCamelCase :List[str] = init_layernorm_from_vision_encoder if text_config is None: UpperCamelCase :Union[str, Any] = {} logger.info('''`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.''' ) if vision_config is None: UpperCamelCase :Any = {} logger.info('''`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.''' ) UpperCamelCase :str = BridgeTowerTextConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = BridgeTowerVisionConfig(**SCREAMING_SNAKE_CASE_ ) @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> str: return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :str = copy.deepcopy(self.__dict__ ) UpperCamelCase :Optional[int] = self.text_config.to_dict() UpperCamelCase :Optional[Any] = self.vision_config.to_dict() UpperCamelCase :Tuple = self.__class__.model_type return output
259
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ ( lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : int =DDIMPipeline UpperCamelCase_ : str =UNCONDITIONAL_IMAGE_GENERATION_PARAMS UpperCamelCase_ : str =PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } UpperCamelCase_ : Optional[Any] =UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS UpperCamelCase_ : List[str] =False def UpperCAmelCase ( self ) -> Any: torch.manual_seed(0 ) UpperCamelCase :Optional[int] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Any = {'''unet''': unet, '''scheduler''': scheduler} return components def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Any: if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): UpperCamelCase :List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase :List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Optional[int] = '''cpu''' UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Optional[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase :str = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) UpperCamelCase :Tuple = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) UpperCamelCase :List[str] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def UpperCAmelCase ( self ) -> int: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Optional[int]: super().test_save_load_local(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Any: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = '''google/ddpm-cifar10-32''' UpperCamelCase :Union[str, Any] = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Tuple = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddim.to(SCREAMING_SNAKE_CASE_ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddim(generator=SCREAMING_SNAKE_CASE_ , eta=0.0 , output_type='''numpy''' ).images UpperCamelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :Tuple = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[Any] = '''google/ddpm-ema-bedroom-256''' UpperCamelCase :Any = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddpm.to(SCREAMING_SNAKE_CASE_ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddpm(generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCamelCase :Dict = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
259
1
from __future__ import annotations from math import pi, sqrt def _A ( SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float ): if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
259
from json import JSONDecodeError # Workaround for requests.exceptions.JSONDecodeError import requests def _A ( SCREAMING_SNAKE_CASE__ : str = "isbn/0140328726" ): UpperCamelCase :Optional[int] = olid.strip().strip('''/''' ) # Remove leading/trailing whitespace & slashes if new_olid.count('''/''' ) != 1: UpperCamelCase :str = F'''{olid} is not a valid Open Library olid''' raise ValueError(SCREAMING_SNAKE_CASE__ ) return requests.get(F'''https://openlibrary.org/{new_olid}.json''' ).json() def _A ( SCREAMING_SNAKE_CASE__ : dict ): UpperCamelCase :str = { '''title''': '''Title''', '''publish_date''': '''Publish date''', '''authors''': '''Authors''', '''number_of_pages''': '''Number of pages:''', '''first_sentence''': '''First sentence''', '''isbn_10''': '''ISBN (10)''', '''isbn_13''': '''ISBN (13)''', } UpperCamelCase :Optional[Any] = {better_key: ol_book_data[key] for key, better_key in desired_keys.items()} UpperCamelCase :List[str] = [ get_openlibrary_data(author['''key'''] )['''name'''] for author in data['''Authors'''] ] UpperCamelCase :int = data['''First sentence''']['''value'''] for key, value in data.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): UpperCamelCase :List[str] = ''', '''.join(SCREAMING_SNAKE_CASE__ ) return data if __name__ == "__main__": import doctest doctest.testmod() while True: __snake_case = input("""\nEnter the ISBN code to search (or 'quit' to stop): """).strip() if isbn.lower() in ("", "q", "quit", "exit", "stop"): break if len(isbn) not in (10, 13) or not isbn.isdigit(): print(f'''Sorry, {isbn} is not a valid ISBN. Please, input a valid ISBN.''') continue print(f'''\nSearching Open Library for ISBN: {isbn}...\n''') try: __snake_case = summarize_book(get_openlibrary_data(f'''isbn/{isbn}''')) print("""\n""".join(f'''{key}: {value}''' for key, value in book_summary.items())) except JSONDecodeError: # Workaround for requests.exceptions.RequestException: print(f'''Sorry, there are no results for ISBN: {isbn}.''')
259
1
import math __snake_case = 10 __snake_case = 7 __snake_case = BALLS_PER_COLOUR * NUM_COLOURS def _A ( SCREAMING_SNAKE_CASE__ : int = 20 ): UpperCamelCase :Optional[Any] = math.comb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = math.comb(NUM_BALLS - BALLS_PER_COLOUR , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = NUM_COLOURS * (1 - missing_colour / total) return F'''{result:.9f}''' if __name__ == "__main__": print(solution(20))
259
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin __snake_case = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=14 , SCREAMING_SNAKE_CASE_=10 , SCREAMING_SNAKE_CASE_=19 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=[1, 2, 3, 4, 5] , SCREAMING_SNAKE_CASE_=25 , SCREAMING_SNAKE_CASE_=5 , ) -> str: UpperCamelCase :Any = d_model UpperCamelCase :List[str] = parent UpperCamelCase :List[Any] = batch_size UpperCamelCase :str = prediction_length UpperCamelCase :str = context_length UpperCamelCase :int = cardinality UpperCamelCase :Optional[Any] = num_time_features UpperCamelCase :Optional[Any] = lags_sequence UpperCamelCase :str = embedding_dimension UpperCamelCase :str = is_training UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :int = num_attention_heads UpperCamelCase :Tuple = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :List[Any] = attention_probs_dropout_prob UpperCamelCase :Optional[int] = context_length UpperCamelCase :Tuple = prediction_length + label_length UpperCamelCase :Optional[Any] = label_length UpperCamelCase :Optional[int] = moving_average UpperCamelCase :Union[str, Any] = autocorrelation_factor def UpperCAmelCase ( self ) -> Optional[int]: return AutoformerConfig( d_model=self.d_model , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , prediction_length=self.prediction_length , context_length=self.context_length , label_length=self.label_length , lags_sequence=self.lags_sequence , num_time_features=self.num_time_features , num_static_categorical_features=1 , cardinality=[self.cardinality] , embedding_dimension=[self.embedding_dimension] , moving_average=self.moving_average , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase :Optional[Any] = config.context_length + max(config.lags_sequence ) UpperCamelCase :Union[str, Any] = ids_tensor([self.batch_size, 1] , config.cardinality[0] ) UpperCamelCase :List[str] = floats_tensor([self.batch_size, _past_length, config.num_time_features] ) UpperCamelCase :Union[str, Any] = floats_tensor([self.batch_size, _past_length] ) UpperCamelCase :Any = floats_tensor([self.batch_size, _past_length] ) > 0.5 # decoder inputs UpperCamelCase :Tuple = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features] ) UpperCamelCase :int = floats_tensor([self.batch_size, config.prediction_length] ) UpperCamelCase :Union[str, Any] = { '''past_values''': past_values, '''static_categorical_features''': static_categorical_features, '''past_time_features''': past_time_features, '''past_observed_mask''': past_observed_mask, '''future_time_features''': future_time_features, '''future_values''': future_values, } return inputs_dict def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :int = self.get_config() UpperCamelCase :Union[str, Any] = self.prepare_autoformer_inputs_dict(SCREAMING_SNAKE_CASE_ ) return config, inputs_dict def UpperCAmelCase ( self ) -> Any: UpperCamelCase , UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: UpperCamelCase :int = AutoformerModel(config=SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ).eval() UpperCamelCase :Any = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = outputs.encoder_last_hidden_state UpperCamelCase :str = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Any = model.get_encoder() encoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = AutoformerEncoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = model.create_network_inputs(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...] ) UpperCamelCase :Tuple = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]) , dim=-1 , ) UpperCamelCase :Optional[Any] = encoder(inputs_embeds=SCREAMING_SNAKE_CASE_ )[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) UpperCamelCase :Optional[Any] = ( torch.mean(transformer_inputs[:, : config.context_length, ...] , dim=1 ) .unsqueeze(1 ) .repeat(1 , config.prediction_length , 1 ) ) UpperCamelCase :Union[str, Any] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]] , device=enc_input.device , ) UpperCamelCase :Tuple = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) UpperCamelCase :Optional[Any] = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean) , dim=1 ), feature[:, config.context_length - config.label_length :, ...], ) , dim=-1 , ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase :Union[str, Any] = model.get_decoder() decoder.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = AutoformerDecoder.from_pretrained(SCREAMING_SNAKE_CASE_ ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = decoder( trend=SCREAMING_SNAKE_CASE_ , inputs_embeds=SCREAMING_SNAKE_CASE_ , encoder_hidden_states=SCREAMING_SNAKE_CASE_ , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[str] =(AutoformerModel, AutoformerForPrediction) if is_torch_available() else () UpperCamelCase_ : List[str] =(AutoformerForPrediction,) if is_torch_available() else () UpperCamelCase_ : Optional[Any] ={'feature-extraction': AutoformerModel} if is_torch_available() else {} UpperCamelCase_ : Any =False UpperCamelCase_ : List[str] =False UpperCamelCase_ : Dict =False UpperCamelCase_ : Dict =False UpperCamelCase_ : int =False UpperCamelCase_ : Optional[int] =False def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = AutoformerModelTester(self ) UpperCamelCase :int = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase , UpperCamelCase :str = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: UpperCamelCase :Optional[int] = model_class(SCREAMING_SNAKE_CASE_ ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :List[str] = model_class.from_pretrained(SCREAMING_SNAKE_CASE_ , output_loading_info=SCREAMING_SNAKE_CASE_ ) self.assertEqual(info['''missing_keys'''] , [] ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*SCREAMING_SNAKE_CASE_ ) @unittest.skip(reason='''Model has no tokens embeddings''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :str = inspect.signature(getattr(SCREAMING_SNAKE_CASE_ , '''forward''' ) ) # The main input is the name of the argument after `self` UpperCamelCase :List[str] = list(model_signature.parameters.keys() )[1] self.assertEqual(AutoformerModel.main_input_name , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase , UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Tuple = [*signature.parameters.keys()] UpperCamelCase :Optional[Any] = [ '''past_values''', '''past_time_features''', '''past_observed_mask''', '''static_categorical_features''', '''static_real_features''', '''future_values''', '''future_time_features''', ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('''future_observed_mask''' ) expected_arg_names.extend( [ '''decoder_attention_mask''', '''head_mask''', '''decoder_head_mask''', '''cross_attn_head_mask''', '''encoder_outputs''', '''past_key_values''', '''output_hidden_states''', '''output_attentions''', '''use_cache''', '''return_dict''', ] ) self.assertListEqual(arg_names[: len(SCREAMING_SNAKE_CASE_ )] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase , UpperCamelCase :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = True UpperCamelCase :Dict = getattr(self.model_tester , '''seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = getattr(self.model_tester , '''decoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = getattr(self.model_tester , '''encoder_seq_length''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = getattr(self.model_tester , '''d_model''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = getattr(self.model_tester , '''num_attention_heads''' , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = d_model // num_attention_heads for model_class in self.all_model_classes: UpperCamelCase :Tuple = True UpperCamelCase :Tuple = False UpperCamelCase :Any = True UpperCamelCase :List[Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :int = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) UpperCamelCase :List[str] = len(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # decoder attentions UpperCamelCase :Union[str, Any] = outputs.decoder_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # cross attentions UpperCamelCase :Union[str, Any] = outputs.cross_attentions self.assertIsInstance(SCREAMING_SNAKE_CASE_ , (list, tuple) ) self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(cross_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, decoder_seq_length, dim] , ) # Check attention is always last and order is fine UpperCamelCase :Any = True UpperCamelCase :int = True UpperCamelCase :Any = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() with torch.no_grad(): UpperCamelCase :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) self.assertEqual(out_len + 2 , len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :List[str] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, encoder_seq_length, dim] , ) @is_flaky() def UpperCAmelCase ( self ) -> List[Any]: super().test_retain_grad_hidden_states_attentions() def _A ( SCREAMING_SNAKE_CASE__ : int="train-batch.pt" ): UpperCamelCase :Union[str, Any] = hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch''' , filename=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) UpperCamelCase :Tuple = torch.load(SCREAMING_SNAKE_CASE__ , map_location=SCREAMING_SNAKE_CASE__ ) return batch @require_torch @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :int = AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = prepare_batch() with torch.no_grad(): UpperCamelCase :Optional[Any] = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , future_values=batch['''future_values'''] , future_time_features=batch['''future_time_features'''] , )[0] UpperCamelCase :Union[str, Any] = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = torch.tensor( [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Dict = model( past_values=batch['''past_values'''] , past_time_features=batch['''past_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , static_categorical_features=batch['''static_categorical_features'''] , ).encoder_last_hidden_state UpperCamelCase :Union[str, Any] = torch.Size((64, model.config.context_length, model.config.d_model) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = torch.tensor( [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]] , device=SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(output[0, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=SCREAMING_SNAKE_CASE_ ) ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = prepare_batch('''val-batch.pt''' ) with torch.no_grad(): UpperCamelCase :Tuple = model.generate( static_categorical_features=batch['''static_categorical_features'''] , past_time_features=batch['''past_time_features'''] , past_values=batch['''past_values'''] , future_time_features=batch['''future_time_features'''] , past_observed_mask=batch['''past_observed_mask'''] , ) UpperCamelCase :Optional[int] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length) ) self.assertEqual(outputs.sequences.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.tensor([3130.6763, 4056.5293, 7053.0786] , device=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = outputs.sequences.mean(dim=1 ) self.assertTrue(torch.allclose(mean_prediction[0, -3:] , SCREAMING_SNAKE_CASE_ , rtol=1e-1 ) )
259
1
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( """The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion""" ) __snake_case = None __snake_case = { """7B""": 1_10_08, """13B""": 1_38_24, """30B""": 1_79_20, """65B""": 2_20_16, """70B""": 2_86_72, } __snake_case = { """7B""": 1, """7Bf""": 1, """13B""": 2, """13Bf""": 2, """30B""": 4, """65B""": 8, """70B""": 8, """70Bf""": 8, } def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : str=256 ): return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def _A ( SCREAMING_SNAKE_CASE__ : Tuple ): with open(SCREAMING_SNAKE_CASE__ , '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict ): with open(SCREAMING_SNAKE_CASE__ , '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple=True ): os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = os.path.join(SCREAMING_SNAKE_CASE__ , '''tmp''' ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = read_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''params.json''' ) ) UpperCamelCase :int = NUM_SHARDS[model_size] UpperCamelCase :Dict = params['''n_layers'''] UpperCamelCase :Tuple = params['''n_heads'''] UpperCamelCase :Any = n_heads // num_shards UpperCamelCase :Optional[Any] = params['''dim'''] UpperCamelCase :List[str] = dim // n_heads UpperCamelCase :List[Any] = 1_00_00.0 UpperCamelCase :Optional[int] = 1.0 / (base ** (torch.arange(0 , SCREAMING_SNAKE_CASE__ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: UpperCamelCase :List[str] = params['''n_kv_heads'''] # for GQA / MQA UpperCamelCase :int = n_heads_per_shard // num_key_value_heads UpperCamelCase :List[Any] = dim // num_key_value_heads else: # compatibility with other checkpoints UpperCamelCase :int = n_heads UpperCamelCase :Dict = n_heads_per_shard UpperCamelCase :List[str] = dim # permute for sliced rotary def permute(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=n_heads , SCREAMING_SNAKE_CASE__ : str=dim , SCREAMING_SNAKE_CASE__ : Any=dim ): return w.view(SCREAMING_SNAKE_CASE__ , dima // n_heads // 2 , 2 , SCREAMING_SNAKE_CASE__ ).transpose(1 , 2 ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(F'''Fetching all parameters from the checkpoint at {input_base_path}.''' ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) UpperCamelCase :Optional[Any] = torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , '''consolidated.00.pth''' ) , map_location='''cpu''' ) else: # Sharded UpperCamelCase :Union[str, Any] = [ torch.load(os.path.join(SCREAMING_SNAKE_CASE__ , F'''consolidated.{i:02d}.pth''' ) , map_location='''cpu''' ) for i in range(SCREAMING_SNAKE_CASE__ ) ] UpperCamelCase :Dict = 0 UpperCamelCase :List[Any] = {'''weight_map''': {}} for layer_i in range(SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[int] = F'''pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded UpperCamelCase :int = { F'''model.layers.{layer_i}.self_attn.q_proj.weight''': permute( loaded[F'''layers.{layer_i}.attention.wq.weight'''] ), F'''model.layers.{layer_i}.self_attn.k_proj.weight''': permute( loaded[F'''layers.{layer_i}.attention.wk.weight'''] ), F'''model.layers.{layer_i}.self_attn.v_proj.weight''': loaded[F'''layers.{layer_i}.attention.wv.weight'''], F'''model.layers.{layer_i}.self_attn.o_proj.weight''': loaded[F'''layers.{layer_i}.attention.wo.weight'''], F'''model.layers.{layer_i}.mlp.gate_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w1.weight'''], F'''model.layers.{layer_i}.mlp.down_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w2.weight'''], F'''model.layers.{layer_i}.mlp.up_proj.weight''': loaded[F'''layers.{layer_i}.feed_forward.w3.weight'''], F'''model.layers.{layer_i}.input_layernorm.weight''': loaded[F'''layers.{layer_i}.attention_norm.weight'''], F'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[F'''layers.{layer_i}.ffn_norm.weight'''], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. UpperCamelCase :Optional[int] = { F'''model.layers.{layer_i}.input_layernorm.weight''': loaded[0][ F'''layers.{layer_i}.attention_norm.weight''' ].clone(), F'''model.layers.{layer_i}.post_attention_layernorm.weight''': loaded[0][ F'''layers.{layer_i}.ffn_norm.weight''' ].clone(), } UpperCamelCase :Optional[int] = permute( torch.cat( [ loaded[i][F'''layers.{layer_i}.attention.wq.weight'''].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) UpperCamelCase :List[Any] = permute( torch.cat( [ loaded[i][F'''layers.{layer_i}.attention.wk.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) UpperCamelCase :int = torch.cat( [ loaded[i][F'''layers.{layer_i}.attention.wv.weight'''].view( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ] , dim=0 , ).reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = torch.cat( [loaded[i][F'''layers.{layer_i}.attention.wo.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) UpperCamelCase :Union[str, Any] = torch.cat( [loaded[i][F'''layers.{layer_i}.feed_forward.w1.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) UpperCamelCase :Dict = torch.cat( [loaded[i][F'''layers.{layer_i}.feed_forward.w2.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ) UpperCamelCase :str = torch.cat( [loaded[i][F'''layers.{layer_i}.feed_forward.w3.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ) UpperCamelCase :str = inv_freq for k, v in state_dict.items(): UpperCamelCase :List[Any] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) UpperCamelCase :List[str] = F'''pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin''' if model_size == "7B": # Unsharded UpperCamelCase :Optional[int] = { '''model.embed_tokens.weight''': loaded['''tok_embeddings.weight'''], '''model.norm.weight''': loaded['''norm.weight'''], '''lm_head.weight''': loaded['''output.weight'''], } else: UpperCamelCase :List[Any] = { '''model.norm.weight''': loaded[0]['''norm.weight'''], '''model.embed_tokens.weight''': torch.cat( [loaded[i]['''tok_embeddings.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=1 ), '''lm_head.weight''': torch.cat([loaded[i]['''output.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )] , dim=0 ), } for k, v in state_dict.items(): UpperCamelCase :Union[str, Any] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # Write configs UpperCamelCase :Optional[int] = {'''total_size''': param_count * 2} write_json(SCREAMING_SNAKE_CASE__ , os.path.join(SCREAMING_SNAKE_CASE__ , '''pytorch_model.bin.index.json''' ) ) UpperCamelCase :Tuple = params['''ffn_dim_multiplier'''] if '''ffn_dim_multiplier''' in params else 1 UpperCamelCase :Optional[Any] = params['''multiple_of'''] if '''multiple_of''' in params else 256 UpperCamelCase :Optional[Any] = LlamaConfig( hidden_size=SCREAMING_SNAKE_CASE__ , intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , num_attention_heads=params['''n_heads'''] , num_hidden_layers=params['''n_layers'''] , rms_norm_eps=params['''norm_eps'''] , num_key_value_heads=SCREAMING_SNAKE_CASE__ , ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('''Loading the checkpoint in a Llama model.''' ) UpperCamelCase :Tuple = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ , torch_dtype=torch.floataa , low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ ) # Avoid saving this as part of the config. del model.config._name_or_path print('''Saving in the Transformers format.''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ , safe_serialization=SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] ): # Initialize the tokenizer based on the `spm` model UpperCamelCase :str = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F'''Saving a {tokenizer_class.__name__} to {tokenizer_path}.''' ) UpperCamelCase :Union[str, Any] = tokenizer_class(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) def _A ( ): UpperCamelCase :Dict = argparse.ArgumentParser() parser.add_argument( '''--input_dir''' , help='''Location of LLaMA weights, which contains tokenizer.model and model folders''' , ) parser.add_argument( '''--model_size''' , choices=['''7B''', '''7Bf''', '''13B''', '''13Bf''', '''30B''', '''65B''', '''70B''', '''70Bf''', '''tokenizer_only'''] , ) parser.add_argument( '''--output_dir''' , help='''Location to write HF model and tokenizer''' , ) parser.add_argument('''--safe_serialization''' , type=SCREAMING_SNAKE_CASE__ , help='''Whether or not to save using `safetensors`.''' ) UpperCamelCase :int = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) UpperCamelCase :List[Any] = os.path.join(args.input_dir , '''tokenizer.model''' ) write_tokenizer(args.output_dir , SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
259
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed __snake_case = logging.getLogger(__name__) def _A ( SCREAMING_SNAKE_CASE__ : Dict=2 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Any=16 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 2 ): def get_dataset(SCREAMING_SNAKE_CASE__ : List[Any] ): UpperCamelCase :Union[str, Any] = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(SCREAMING_SNAKE_CASE__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) UpperCamelCase :str = get_dataset(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = get_dataset(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) UpperCamelCase :Any = DataLoader(SCREAMING_SNAKE_CASE__ , shuffle=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any=None ): UpperCamelCase :Dict = [] for epoch in range(SCREAMING_SNAKE_CASE__ ): # Train quickly model.train() for batch in dataloader: UpperCamelCase , UpperCamelCase :Optional[Any] = batch UpperCamelCase :int = model(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = torch.nn.functional.mse_loss(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) accelerator.backward(SCREAMING_SNAKE_CASE__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class UpperCAmelCase_ ( nn.Module ): """simple docstring""" def __init__( self ) -> str: super().__init__() UpperCamelCase :Optional[int] = nn.Parameter(torch.randn(1 ) ) UpperCamelCase :int = nn.Parameter(torch.randn(1 ) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> int: return x * self.a + self.b class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Dict: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Tuple = dummy_dataloaders() UpperCamelCase :Tuple = ProjectConfiguration(total_limit=1 , project_dir=SCREAMING_SNAKE_CASE_ , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :Dict = Accelerator(project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def UpperCAmelCase ( self ) -> str: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[str] = DummyModel() UpperCamelCase :Union[str, Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Dict = dummy_dataloaders() # Train baseline UpperCamelCase :Dict = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :int = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial UpperCamelCase :int = os.path.join(SCREAMING_SNAKE_CASE_ , '''initial''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[Any] = model.a.item(), model.b.item() UpperCamelCase :Optional[int] = optimizer.state_dict() UpperCamelCase :Optional[int] = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Dict = model.a.item(), model.b.item() UpperCamelCase :Optional[Any] = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase :Any = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :List[Any] = dummy_dataloaders() UpperCamelCase :List[str] = Accelerator() UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Tuple = model.a.item(), model.b.item() UpperCamelCase :Tuple = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything UpperCamelCase :Optional[int] = os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoint''' ) accelerator.save_state(SCREAMING_SNAKE_CASE_ ) # Load everything back in and make sure all states work accelerator.load_state(SCREAMING_SNAKE_CASE_ ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Union[str, Any] = model.a.item(), model.b.item() UpperCamelCase :Optional[Any] = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[Any] = DummyModel() UpperCamelCase :Optional[int] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :int = dummy_dataloaders() UpperCamelCase :int = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :Union[str, Any] = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() ((UpperCamelCase) , (UpperCamelCase)) :List[str] = model.a.item(), model.b.item() UpperCamelCase :Dict = optimizer.state_dict() UpperCamelCase :Any = train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[int] = model.a.item(), model.b.item() UpperCamelCase :Any = optimizer.state_dict() # Train partially set_seed(42 ) UpperCamelCase :Union[str, Any] = DummyModel() UpperCamelCase :List[Any] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase , UpperCamelCase :Tuple = dummy_dataloaders() UpperCamelCase :Optional[Any] = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ((UpperCamelCase) , (UpperCamelCase)) :Dict = model.a.item(), model.b.item() UpperCamelCase :Dict = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = train(2 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_1''' ) ) test_rands += train(1 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ((UpperCamelCase) , (UpperCamelCase)) :Optional[Any] = model.a.item(), model.b.item() UpperCamelCase :str = optimizer.state_dict() self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[Any] = torch.tensor([1, 2, 3] ) UpperCamelCase :Any = torch.tensor([2, 3, 4] ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :Optional[Any] = torch.optim.Adam(net.parameters() ) UpperCamelCase :Optional[Any] = Accelerator() with self.assertRaises(SCREAMING_SNAKE_CASE_ ) as ve: accelerator.register_for_checkpointing(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = str(ve.exception ) self.assertTrue('''Item at index 0''' in message ) self.assertTrue('''Item at index 1''' in message ) self.assertFalse('''Item at index 2''' in message ) self.assertFalse('''Item at index 3''' in message ) def UpperCAmelCase ( self ) -> Any: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :List[Any] = DummyModel() UpperCamelCase :List[str] = torch.optim.Adam(params=model.parameters() , lr=1e-3 ) UpperCamelCase :Any = torch.optim.lr_scheduler.StepLR(SCREAMING_SNAKE_CASE_ , step_size=1 , gamma=0.99 ) UpperCamelCase , UpperCamelCase :Any = dummy_dataloaders() UpperCamelCase :Optional[int] = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ ) # Train baseline UpperCamelCase :str = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Tuple = accelerator.prepare( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Save initial accelerator.save_state() UpperCamelCase :int = scheduler.state_dict() train(3 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) self.assertNotEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) self.assertEqual(SCREAMING_SNAKE_CASE_ , scheduler.state_dict() ) def UpperCAmelCase ( self ) -> Union[str, Any]: with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) UpperCamelCase :Optional[Any] = DummyModel() UpperCamelCase :int = ProjectConfiguration(automatic_checkpoint_naming=SCREAMING_SNAKE_CASE_ , total_limit=2 ) # Train baseline UpperCamelCase :Tuple = Accelerator(project_dir=SCREAMING_SNAKE_CASE_ , project_config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = accelerator.prepare(SCREAMING_SNAKE_CASE_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_0''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_9''' ) ) ) self.assertTrue(os.path.exists(os.path.join(SCREAMING_SNAKE_CASE_ , '''checkpoints''' , '''checkpoint_10''' ) ) ) @require_cuda def UpperCAmelCase ( self ) -> int: UpperCamelCase :int = ['''torchrun''', F'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] execute_subprocess_async(SCREAMING_SNAKE_CASE_ , env=os.environ.copy() ) if __name__ == "__main__": __snake_case = """/tmp/accelerate/state_checkpointing""" __snake_case = DummyModel() __snake_case = torch.optim.Adam(params=model.parameters(), lr=1E-3) __snake_case = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.9_9) __snake_case , __snake_case = dummy_dataloaders() __snake_case = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline __snake_case = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision="""no""") if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) __snake_case , __snake_case , __snake_case , __snake_case , __snake_case = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) __snake_case , __snake_case = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert param_device.type == accelerator.device.type __snake_case = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""cpu""") for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert ( param_device.type == torch.device("""cpu""").type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""on_device""") for group in optimizer.param_groups: __snake_case = group["""params"""][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match="""Unsupported optimizer map location passed"""): accelerator.load_state(os.path.join(savedir, """checkpoints""", """checkpoint_0"""), map_location="""invalid""") accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
259
1
import os import sys import tempfile import torch from .state import AcceleratorState from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment def _A ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str]=() , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]="no" , SCREAMING_SNAKE_CASE__ : Dict="29500" ): UpperCamelCase :List[Any] = False UpperCamelCase :Tuple = False if any(key.startswith('''KAGGLE''' ) for key in os.environ.keys() ): UpperCamelCase :Dict = True elif "IPython" in sys.modules: UpperCamelCase :int = '''google.colab''' in str(sys.modules['''IPython'''].get_ipython() ) try: UpperCamelCase :Any = PrecisionType(mixed_precision.lower() ) except ValueError: raise ValueError( F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.''' ) if (in_colab or in_kaggle) and (os.environ.get('''TPU_NAME''' , SCREAMING_SNAKE_CASE__ ) is not None): # TPU launch import torch_xla.distributed.xla_multiprocessing as xmp if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside ''' '''your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if num_processes is None: UpperCamelCase :Tuple = 8 UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''TPU''' ) print(F'''Launching a training on {num_processes} TPU cores.''' ) xmp.spawn(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) elif in_colab: # No need for a distributed launch otherwise as it's either CPU or one GPU. if torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on one CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) else: if num_processes is None: raise ValueError( '''You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.''' ) if num_processes > 1: # Multi-GPU launch from torch.multiprocessing import start_processes from torch.multiprocessing.spawn import ProcessRaisedException if len(AcceleratorState._shared_state ) > 0: raise ValueError( '''To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized ''' '''inside your training function. Restart your notebook and make sure no cells initializes an ''' '''`Accelerator`.''' ) if torch.cuda.is_initialized(): raise ValueError( '''To launch a multi-GPU training from your notebook, you need to avoid running any instruction ''' '''using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA ''' '''function.''' ) # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port=SCREAMING_SNAKE_CASE__ , mixed_precision=SCREAMING_SNAKE_CASE__ ): UpperCamelCase :Optional[Any] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , distributed_type='''MULTI_GPU''' ) print(F'''Launching training on {num_processes} GPUs.''' ) try: start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' ) except ProcessRaisedException as e: if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: raise RuntimeError( '''CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. ''' '''This likely stems from an outside import causing issues once the `notebook_launcher()` is called. ''' '''Please review your imports and test them when running the `notebook_launcher()` to identify ''' '''which one is problematic.''' ) from e else: # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. if is_mps_available(): UpperCamelCase :Any = '''1''' print('''Launching training on MPS.''' ) elif torch.cuda.is_available(): print('''Launching training on one GPU.''' ) else: print('''Launching training on CPU.''' ) function(*SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple=() , SCREAMING_SNAKE_CASE__ : int=2 ): from torch.multiprocessing import start_processes with tempfile.NamedTemporaryFile() as tmp_file: # torch.distributed will expect a few environment variable to be here. We set the ones common to each # process here (the other ones will be set be the launcher). with patch_environment( world_size=SCREAMING_SNAKE_CASE__ , master_addr='''127.0.01''' , master_port='''29500''' , accelerate_mixed_precision='''no''' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='''yes''' , ): UpperCamelCase :Optional[int] = PrepareForLaunch(SCREAMING_SNAKE_CASE__ , debug=SCREAMING_SNAKE_CASE__ ) start_processes(SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , nprocs=SCREAMING_SNAKE_CASE__ , start_method='''fork''' )
259
import numpy as np __snake_case = [ ["""a""", """b""", """c""", """d""", """e"""], ["""f""", """g""", """h""", """i""", """k"""], ["""l""", """m""", """n""", """o""", """p"""], ["""q""", """r""", """s""", """t""", """u"""], ["""v""", """w""", """x""", """y""", """z"""], ] class UpperCAmelCase_ : """simple docstring""" def __init__( self ) -> None: UpperCamelCase :Dict = np.array(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> np.ndarray: UpperCamelCase , UpperCamelCase :Tuple = np.where(letter == self.SQUARE ) UpperCamelCase :List[Any] = np.concatenate([indexa + 1, indexa + 1] ) return indexes def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :int = self.SQUARE[indexa - 1, indexa - 1] return letter def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Any = message.lower() UpperCamelCase :int = message.replace(''' ''' , '''''' ) UpperCamelCase :Dict = message.replace('''j''' , '''i''' ) UpperCamelCase :str = np.empty((2, len(SCREAMING_SNAKE_CASE_ )) ) for letter_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Dict = self.letter_to_numbers(message[letter_index] ) UpperCamelCase :Union[str, Any] = numbers[0] UpperCamelCase :Dict = numbers[1] UpperCamelCase :Any = first_step.reshape(2 * len(SCREAMING_SNAKE_CASE_ ) ) UpperCamelCase :Union[str, Any] = '''''' for numbers_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Dict = int(second_step[numbers_index * 2] ) UpperCamelCase :List[str] = int(second_step[(numbers_index * 2) + 1] ) UpperCamelCase :Tuple = self.numbers_to_letter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = encoded_message + letter return encoded_message def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase :Any = message.lower() message.replace(''' ''' , '''''' ) UpperCamelCase :Optional[int] = np.empty(2 * len(SCREAMING_SNAKE_CASE_ ) ) for letter_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :List[str] = self.letter_to_numbers(message[letter_index] ) UpperCamelCase :Dict = numbers[0] UpperCamelCase :List[str] = numbers[1] UpperCamelCase :int = first_step.reshape((2, len(SCREAMING_SNAKE_CASE_ )) ) UpperCamelCase :Any = '''''' for numbers_index in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :Any = int(second_step[0, numbers_index] ) UpperCamelCase :List[Any] = int(second_step[1, numbers_index] ) UpperCamelCase :Tuple = self.numbers_to_letter(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = decoded_message + letter return decoded_message
259
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 __snake_case = logging.get_logger(__name__) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] =['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: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = size if size is not None else {'''shortest_edge''': 224} UpperCamelCase :Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = crop_size if crop_size is not None else {'''height''': 256, '''width''': 256} UpperCamelCase :Union[str, Any] = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) UpperCamelCase :int = do_resize UpperCamelCase :str = size UpperCamelCase :str = resample UpperCamelCase :Dict = do_rescale UpperCamelCase :Dict = rescale_factor UpperCamelCase :List[Any] = do_center_crop UpperCamelCase :Optional[Any] = crop_size UpperCamelCase :Union[str, Any] = 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: UpperCamelCase :List[str] = 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 :Any = 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: UpperCamelCase :Union[str, Any] = 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: 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: 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: UpperCamelCase :Any = do_resize if do_resize is not None else self.do_resize UpperCamelCase :Tuple = resample if resample is not None else self.resample UpperCamelCase :Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCamelCase :Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCamelCase :Any = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCamelCase :Any = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) UpperCamelCase :Dict = size if size is not None else self.size UpperCamelCase :str = get_size_dict(SCREAMING_SNAKE_CASE_ , default_to_square=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = crop_size if crop_size is not None else self.crop_size UpperCamelCase :Optional[Any] = get_size_dict(SCREAMING_SNAKE_CASE_ , param_name='''crop_size''' ) UpperCamelCase :str = 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 :Union[str, Any] = [to_numpy_array(SCREAMING_SNAKE_CASE_ ) for image in images] if do_resize: UpperCamelCase :List[str] = [self.resize(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ , resample=SCREAMING_SNAKE_CASE_ ) for image in images] if do_center_crop: UpperCamelCase :Tuple = [self.center_crop(image=SCREAMING_SNAKE_CASE_ , size=SCREAMING_SNAKE_CASE_ ) for image in images] if do_rescale: UpperCamelCase :Optional[int] = [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 :str = [self.flip_channel_order(image=SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :Any = [to_channel_dimension_format(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) for image in images] UpperCamelCase :Optional[int] = {'''pixel_values''': images} return BatchFeature(data=SCREAMING_SNAKE_CASE_ , tensor_type=SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = None ) -> Dict: UpperCamelCase :str = 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 :Tuple = target_sizes.numpy() UpperCamelCase :Union[str, Any] = [] for idx in range(len(SCREAMING_SNAKE_CASE_ ) ): UpperCamelCase :str = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase :Union[str, Any] = logits.argmax(dim=1 ) UpperCamelCase :str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
259
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def _A ( SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple ): return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any="attention" ): UpperCamelCase :str = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) UpperCamelCase :Optional[Any] = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCamelCase :Optional[int] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) UpperCamelCase :List[Any] = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCamelCase :Union[str, Any] = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) UpperCamelCase :Any = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCamelCase :str = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) UpperCamelCase :str = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str]=False ): if split_mlp_wi: UpperCamelCase :List[Any] = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] UpperCamelCase :int = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] UpperCamelCase :str = (wi_a, wi_a) else: UpperCamelCase :Optional[Any] = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] UpperCamelCase :Optional[int] = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ): return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def _A ( SCREAMING_SNAKE_CASE__ : dict , *, SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool , SCREAMING_SNAKE_CASE__ : bool = False ): UpperCamelCase :Tuple = traverse_util.flatten_dict(variables['''target'''] ) UpperCamelCase :List[Any] = {'''/'''.join(SCREAMING_SNAKE_CASE__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase :int = '''encoder/encoder/mlp/wi_0/kernel''' in old print('''Split MLP:''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = collections.OrderedDict() # Shared embeddings. UpperCamelCase :int = old['''token_embedder/embedding'''] # Encoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :str = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''pre_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[str] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''attention''' ) UpperCamelCase :str = layer_norm UpperCamelCase :Dict = k.T UpperCamelCase :Optional[Any] = o.T UpperCamelCase :int = q.T UpperCamelCase :Any = v.T # Block i, layer 1 (MLP). UpperCamelCase :Tuple = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase , UpperCamelCase :Any = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = layer_norm if split_mlp_wi: UpperCamelCase :List[Any] = wi[0].T UpperCamelCase :Tuple = wi[1].T else: UpperCamelCase :Optional[Any] = wi.T UpperCamelCase :Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :List[str] = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''encoder''' ).T UpperCamelCase :Optional[Any] = old['''encoder/encoder_norm/scale'''] if not scalable_attention: UpperCamelCase :str = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , '''encoder''' ).T UpperCamelCase :Any = tax_relpos_bias_lookup( SCREAMING_SNAKE_CASE__ , 0 , '''decoder''' ).T if not is_encoder_only: # Decoder. for i in range(SCREAMING_SNAKE_CASE__ ): # Block i, layer 0 (Self Attention). UpperCamelCase :Union[str, Any] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_self_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :Dict = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''self_attention''' ) UpperCamelCase :str = layer_norm UpperCamelCase :int = k.T UpperCamelCase :Optional[int] = o.T UpperCamelCase :Tuple = q.T UpperCamelCase :List[str] = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase :str = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase :List[Any] = tax_attention_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''encoder_decoder_attention''' ) UpperCamelCase :Tuple = layer_norm UpperCamelCase :Optional[Any] = k.T UpperCamelCase :List[str] = o.T UpperCamelCase :List[str] = q.T UpperCamelCase :str = v.T # Block i, layer 2 (MLP). UpperCamelCase :List[str] = tax_layer_norm_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , '''pre_mlp_layer_norm''' ) UpperCamelCase , UpperCamelCase :Optional[int] = tax_mlp_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = layer_norm if split_mlp_wi: UpperCamelCase :List[str] = wi[0].T UpperCamelCase :str = wi[1].T else: UpperCamelCase :Dict = wi.T UpperCamelCase :Optional[Any] = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase :Tuple = tax_relpos_bias_lookup(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''decoder''' ).T UpperCamelCase :Union[str, Any] = old['''decoder/decoder_norm/scale'''] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase :Union[str, Any] = old['''decoder/logits_dense/kernel'''].T return new def _A ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : bool ): UpperCamelCase :Optional[int] = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Dict = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase :Dict = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) UpperCamelCase :List[Any] = state_dict['''shared.weight'''] return state_dict def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Any ): UpperCamelCase :Dict = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = convert_tax_to_pytorch( SCREAMING_SNAKE_CASE__ , num_layers=config.num_layers , is_encoder_only=SCREAMING_SNAKE_CASE__ , scalable_attention=SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = make_state_dict(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) def _A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ): UpperCamelCase :Any = MTaConfig.from_json_file(SCREAMING_SNAKE_CASE__ ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase :List[str] = UMTaEncoderModel(SCREAMING_SNAKE_CASE__ ) else: UpperCamelCase :Any = UMTaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Verify that we can load the checkpoint. model.from_pretrained(SCREAMING_SNAKE_CASE__ ) print('''Done''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser(description="""Converts a native T5X checkpoint into a PyTorch checkpoint.""") # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path to the T5X checkpoint.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help="""The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.""", ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) parser.add_argument( """--is_encoder_only""", action="""store_true""", help="""Check if the model is encoder-decoder model""", default=False ) parser.add_argument( """--scalable_attention""", action="""store_true""", help="""Whether the model uses scaled attention (umt5 model)""", default=False, ) __snake_case = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
259
1
def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): UpperCamelCase :Any = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :int = [[False for _ in range(m + 1 )] for _ in range(n + 1 )] UpperCamelCase :List[str] = True for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(m + 1 ): if dp[i][j]: if j < m and a[i].upper() == b[j]: UpperCamelCase :List[Any] = True if a[i].islower(): UpperCamelCase :List[Any] = True return dp[n][m] if __name__ == "__main__": import doctest doctest.testmod()
259
def _A ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] ): UpperCamelCase :Tuple = len(SCREAMING_SNAKE_CASE__ ) print('''The following activities are selected:''' ) # The first activity is always selected UpperCamelCase :Dict = 0 print(SCREAMING_SNAKE_CASE__ , end=''',''' ) # Consider rest of the activities for j in range(SCREAMING_SNAKE_CASE__ ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(SCREAMING_SNAKE_CASE__ , end=''',''' ) UpperCamelCase :List[str] = j if __name__ == "__main__": import doctest doctest.testmod() __snake_case = [1, 3, 0, 5, 8, 5] __snake_case = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
259
1
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/wavlm-base""": """https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json""", # See all WavLM models at https://huggingface.co/models?filter=wavlm } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='wavlm' 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.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_=320 , SCREAMING_SNAKE_CASE_=800 , 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_=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_=80 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=1 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> Union[str, Any]: super().__init__(**SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = hidden_size UpperCamelCase :Dict = feat_extract_norm UpperCamelCase :Optional[Any] = feat_extract_activation UpperCamelCase :Dict = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = conv_bias UpperCamelCase :Dict = num_buckets UpperCamelCase :Dict = max_bucket_distance UpperCamelCase :Optional[int] = num_conv_pos_embeddings UpperCamelCase :str = num_conv_pos_embedding_groups UpperCamelCase :List[str] = len(self.conv_dim ) UpperCamelCase :str = num_hidden_layers UpperCamelCase :Optional[Any] = intermediate_size UpperCamelCase :Union[str, Any] = hidden_act UpperCamelCase :Optional[Any] = num_attention_heads UpperCamelCase :Union[str, Any] = hidden_dropout UpperCamelCase :Any = attention_dropout UpperCamelCase :Any = activation_dropout UpperCamelCase :str = feat_proj_dropout UpperCamelCase :Any = final_dropout UpperCamelCase :Dict = layerdrop UpperCamelCase :List[Any] = layer_norm_eps UpperCamelCase :Tuple = initializer_range UpperCamelCase :Union[str, Any] = num_ctc_classes UpperCamelCase :Optional[Any] = vocab_size UpperCamelCase :Union[str, Any] = do_stable_layer_norm UpperCamelCase :Optional[Any] = use_weighted_layer_sum UpperCamelCase :Optional[int] = classifier_proj_size 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 :Dict = apply_spec_augment UpperCamelCase :int = mask_time_prob UpperCamelCase :Dict = mask_time_length UpperCamelCase :Optional[int] = mask_time_min_masks UpperCamelCase :Optional[int] = mask_feature_prob UpperCamelCase :Dict = mask_feature_length # parameters for pretraining with codevector quantized representations UpperCamelCase :Dict = num_codevectors_per_group UpperCamelCase :str = num_codevector_groups UpperCamelCase :Dict = contrastive_logits_temperature UpperCamelCase :str = num_negatives UpperCamelCase :Union[str, Any] = codevector_dim UpperCamelCase :int = proj_codevector_dim UpperCamelCase :int = diversity_loss_weight # ctc loss UpperCamelCase :Any = ctc_loss_reduction UpperCamelCase :List[str] = ctc_zero_infinity # adapter UpperCamelCase :Any = add_adapter UpperCamelCase :Union[str, Any] = adapter_kernel_size UpperCamelCase :Dict = adapter_stride UpperCamelCase :List[Any] = num_adapter_layers UpperCamelCase :Any = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. UpperCamelCase :str = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. UpperCamelCase :int = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[Any] = list(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = xvector_output_dim @property def UpperCAmelCase ( self ) -> str: return functools.reduce(operator.mul , self.conv_stride , 1 )
259
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/git-base""": """https://huggingface.co/microsoft/git-base/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Dict ='git_vision_model' def __init__( self , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=3072 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=12 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=224 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_="quick_gelu" , SCREAMING_SNAKE_CASE_=1e-5 , SCREAMING_SNAKE_CASE_=0.0 , SCREAMING_SNAKE_CASE_=0.02 , **SCREAMING_SNAKE_CASE_ , ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = hidden_size UpperCamelCase :Union[str, Any] = intermediate_size UpperCamelCase :Dict = num_hidden_layers UpperCamelCase :int = num_attention_heads UpperCamelCase :List[str] = num_channels UpperCamelCase :Optional[int] = patch_size UpperCamelCase :Optional[int] = image_size UpperCamelCase :List[Any] = initializer_range UpperCamelCase :Union[str, Any] = attention_dropout UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :Optional[Any] = hidden_act @classmethod def UpperCAmelCase ( cls , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase , UpperCamelCase :Dict = cls.get_config_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) # get the vision config dict if we are loading from GITConfig if config_dict.get('''model_type''' ) == "git": UpperCamelCase :Tuple = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'''You are using a model of type {config_dict["model_type"]} to instantiate a model of type ''' F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[Any] ='git' def __init__( self , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=3_0522 , SCREAMING_SNAKE_CASE_=768 , SCREAMING_SNAKE_CASE_=6 , 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_=1024 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=1e-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=101 , SCREAMING_SNAKE_CASE_=102 , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> int: super().__init__(bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , pad_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) if vision_config is None: UpperCamelCase :Tuple = {} logger.info('''vision_config is None. initializing the GitVisionConfig with default values.''' ) UpperCamelCase :Union[str, Any] = GitVisionConfig(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = vocab_size UpperCamelCase :Optional[Any] = hidden_size UpperCamelCase :List[Any] = num_hidden_layers UpperCamelCase :List[Any] = num_attention_heads UpperCamelCase :Dict = hidden_act UpperCamelCase :List[str] = intermediate_size UpperCamelCase :List[str] = hidden_dropout_prob UpperCamelCase :Optional[int] = attention_probs_dropout_prob UpperCamelCase :Optional[Any] = max_position_embeddings UpperCamelCase :Tuple = initializer_range UpperCamelCase :Any = layer_norm_eps UpperCamelCase :int = position_embedding_type UpperCamelCase :Dict = use_cache UpperCamelCase :Tuple = tie_word_embeddings UpperCamelCase :Union[str, Any] = num_image_with_embedding UpperCamelCase :Optional[int] = bos_token_id UpperCamelCase :List[Any] = eos_token_id def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :Union[str, Any] = copy.deepcopy(self.__dict__ ) UpperCamelCase :Optional[int] = self.vision_config.to_dict() UpperCamelCase :int = self.__class__.model_type return output
259
1
from ...configuration_utils import PretrainedConfig from ...utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { """microsoft/markuplm-base""": """https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json""", """microsoft/markuplm-large""": """https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json""", } class UpperCAmelCase_ ( lowercase ): """simple docstring""" UpperCamelCase_ : Optional[int] ='markuplm' def __init__( self , SCREAMING_SNAKE_CASE_=3_0522 , 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-12 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=0 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=256 , SCREAMING_SNAKE_CASE_=1024 , SCREAMING_SNAKE_CASE_=216 , SCREAMING_SNAKE_CASE_=1001 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=50 , SCREAMING_SNAKE_CASE_="absolute" , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , **SCREAMING_SNAKE_CASE_ , ) -> str: super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :str = vocab_size UpperCamelCase :Tuple = hidden_size UpperCamelCase :Dict = num_hidden_layers UpperCamelCase :Any = num_attention_heads UpperCamelCase :Tuple = hidden_act UpperCamelCase :Any = intermediate_size UpperCamelCase :List[Any] = hidden_dropout_prob UpperCamelCase :Dict = attention_probs_dropout_prob UpperCamelCase :List[Any] = max_position_embeddings UpperCamelCase :List[Any] = type_vocab_size UpperCamelCase :Any = initializer_range UpperCamelCase :Tuple = layer_norm_eps UpperCamelCase :List[str] = position_embedding_type UpperCamelCase :Dict = use_cache UpperCamelCase :Dict = classifier_dropout # additional properties UpperCamelCase :Any = max_depth UpperCamelCase :Union[str, Any] = max_xpath_tag_unit_embeddings UpperCamelCase :Optional[int] = max_xpath_subs_unit_embeddings UpperCamelCase :str = tag_pad_id UpperCamelCase :List[str] = subs_pad_id UpperCamelCase :Tuple = xpath_unit_hidden_size
259
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder __snake_case = """__DUMMY_TRANSFORMERS_USER__""" __snake_case = """Dummy User""" __snake_case = """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""" __snake_case = """https://hub-ci.huggingface.co""" __snake_case = CI_HUB_ENDPOINT + """/datasets/{repo_id}/resolve/{revision}/{path}""" __snake_case = CI_HUB_ENDPOINT + """/{repo_id}/resolve/{revision}/{filename}""" __snake_case = Path("""~/.huggingface/hub_ci_token""").expanduser() @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Tuple ): monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Any ): monkeypatch.setattr('''datasets.config.HF_ENDPOINT''' , SCREAMING_SNAKE_CASE__ ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : List[str] ): monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] ): HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def _A ( ): return HfApi(endpoint=SCREAMING_SNAKE_CASE__ ) @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi ): UpperCamelCase :Tuple = HfFolder.get_token() HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Dict ): def _cleanup_repo(SCREAMING_SNAKE_CASE__ : Tuple ): hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def _A ( SCREAMING_SNAKE_CASE__ : Tuple ): @contextmanager def _temporary_repo(SCREAMING_SNAKE_CASE__ : Any ): try: yield repo_id finally: cleanup_repo(SCREAMING_SNAKE_CASE__ ) return _temporary_repo @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] ): UpperCamelCase :Union[str, Any] = F'''repo_txt_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :int = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data/text_data.txt''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any ): UpperCamelCase :Optional[int] = F'''repo_zipped_txt_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :Any = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data.zip''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def _A ( SCREAMING_SNAKE_CASE__ : HfApi , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str] ): UpperCamelCase :Dict = F'''repo_zipped_img_data-{int(time.time() * 1_0e3 )}''' UpperCamelCase :Dict = F'''{CI_HUB_USER}/{repo_name}''' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='''data.zip''' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def _A ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): return hf_private_dataset_repo_zipped_img_data_
259
1
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ ) -> Any: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): UpperCamelCase :Tuple = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = '''sshleifer/tiny-gpt2''' UpperCamelCase :int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Optional[int] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :str = '''sgugger/tiny-distilbert-classification''' UpperCamelCase :List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , only_pretrain_model=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :List[str] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = '''sshleifer/tiny-gpt2''' UpperCamelCase :Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :List[Any] = '''sshleifer/tiny-gpt2''' UpperCamelCase :Any = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase :List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = '''sshleifer/tiny-gpt2''' UpperCamelCase :str = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase :int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Dict = '''sshleifer/tiny-gpt2''' UpperCamelCase :List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :int = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = '''sshleifer/tiny-gpt2''' UpperCamelCase :str = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Optional[Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , [config] ) UpperCamelCase :Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase :List[Any] = '''patrickvonplaten/t5-tiny-random''' UpperCamelCase :int = AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :List[Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ , configs=[config] ) UpperCamelCase :Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , '''Cannot do xla on CPU.''' ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Optional[Any] = '''sshleifer/tiny-gpt2''' UpperCamelCase :str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=SCREAMING_SNAKE_CASE_ , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Union[str, Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase ( self ) -> List[str]: UpperCamelCase :Any = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase :Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , save_to_csv=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , '''inf_time.csv''' ) , inference_memory_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , '''inf_mem.csv''' ) , env_info_csv_file=os.path.join(SCREAMING_SNAKE_CASE_ , '''env.csv''' ) , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :Optional[Any] = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) benchmark.run() self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , '''env.csv''' ) ).exists() ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Union[str, Any] = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(SCREAMING_SNAKE_CASE_ ): self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''sequential''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''cumulative''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''current''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCamelCase :Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=SCREAMING_SNAKE_CASE_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(SCREAMING_SNAKE_CASE_ , '''log.txt''' ) , log_print=SCREAMING_SNAKE_CASE_ , trace_memory_line_by_line=SCREAMING_SNAKE_CASE_ , eager_mode=SCREAMING_SNAKE_CASE_ , multi_process=SCREAMING_SNAKE_CASE_ , ) UpperCamelCase :str = TensorFlowBenchmark(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(SCREAMING_SNAKE_CASE_ , '''log.txt''' ) ).exists() )
259
from __future__ import annotations import unittest from transformers import RoFormerConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerModel, ) from transformers.models.roformer.modeling_tf_roformer import ( TFRoFormerSelfAttention, TFRoFormerSinusoidalPositionalEmbedding, ) class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , 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_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , ) -> Dict: UpperCamelCase :Any = parent UpperCamelCase :Dict = 13 UpperCamelCase :List[Any] = 7 UpperCamelCase :List[Any] = True UpperCamelCase :Dict = True UpperCamelCase :Union[str, Any] = True UpperCamelCase :List[str] = True UpperCamelCase :Dict = 99 UpperCamelCase :Any = 32 UpperCamelCase :Tuple = 2 UpperCamelCase :Union[str, Any] = 4 UpperCamelCase :List[str] = 37 UpperCamelCase :Dict = '''gelu''' UpperCamelCase :Dict = 0.1 UpperCamelCase :Tuple = 0.1 UpperCamelCase :Dict = 512 UpperCamelCase :str = 16 UpperCamelCase :Optional[Any] = 2 UpperCamelCase :Dict = 0.02 UpperCamelCase :Optional[int] = 3 UpperCamelCase :int = 4 UpperCamelCase :Dict = None def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase :Optional[int] = None if self.use_input_mask: UpperCamelCase :Dict = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase :Dict = None if self.use_token_type_ids: UpperCamelCase :List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCamelCase :Union[str, Any] = None UpperCamelCase :Optional[int] = None UpperCamelCase :Any = None if self.use_labels: UpperCamelCase :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase :int = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase :Union[str, Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , return_dict=SCREAMING_SNAKE_CASE_ , ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_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_ ) -> Optional[int]: UpperCamelCase :Optional[Any] = TFRoFormerModel(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids} UpperCamelCase :int = [input_ids, input_mask] UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.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_ ) -> int: UpperCamelCase :List[Any] = True UpperCamelCase :Union[str, Any] = TFRoFormerForCausalLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Any = model(SCREAMING_SNAKE_CASE_ )['''logits'''] self.parent.assertListEqual( list(prediction_scores.numpy().shape ) , [self.batch_size, self.seq_length, self.vocab_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_ ) -> Union[str, Any]: UpperCamelCase :str = TFRoFormerForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[Any] = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_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_ ) -> List[str]: UpperCamelCase :List[Any] = self.num_labels UpperCamelCase :int = TFRoFormerForSequenceClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Optional[Any] = model(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_ ) -> int: UpperCamelCase :List[Any] = self.num_choices UpperCamelCase :Any = TFRoFormerForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :int = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :Any = tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE_ , 1 ) , (1, self.num_choices, 1) ) UpperCamelCase :List[Any] = { '''input_ids''': multiple_choice_inputs_ids, '''attention_mask''': multiple_choice_input_mask, '''token_type_ids''': multiple_choice_token_type_ids, } UpperCamelCase :Dict = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) 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: UpperCamelCase :Union[str, Any] = self.num_labels UpperCamelCase :Dict = TFRoFormerForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :Tuple = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.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_ ) -> Union[str, Any]: UpperCamelCase :Union[str, Any] = TFRoFormerForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = { '''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids, } UpperCamelCase :List[Any] = model(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 ) -> Tuple: UpperCamelCase :Optional[int] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) :Union[str, Any] = config_and_inputs UpperCamelCase :Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : str =( ( TFRoFormerModel, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerForMultipleChoice, ) if is_tf_available() else () ) UpperCamelCase_ : Tuple =( { 'feature-extraction': TFRoFormerModel, 'fill-mask': TFRoFormerForMaskedLM, 'question-answering': TFRoFormerForQuestionAnswering, 'text-classification': TFRoFormerForSequenceClassification, 'text-generation': TFRoFormerForCausalLM, 'token-classification': TFRoFormerForTokenClassification, 'zero-shot': TFRoFormerForSequenceClassification, } if is_tf_available() else {} ) UpperCamelCase_ : Tuple =False UpperCamelCase_ : Optional[Any] =False def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: if pipeline_test_casse_name == "TextGenerationPipelineTests": return True return False def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Any = TFRoFormerModelTester(self ) UpperCamelCase :Optional[int] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> List[str]: self.config_tester.run_common_tests() def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> str: UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE_ ) @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Dict = TFRoFormerModel.from_pretrained('''junnyu/roformer_chinese_base''' ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Tuple = TFRoFormerForMaskedLM.from_pretrained('''junnyu/roformer_chinese_base''' ) UpperCamelCase :Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCamelCase :str = model(SCREAMING_SNAKE_CASE_ )[0] # TODO Replace vocab size UpperCamelCase :Tuple = 5_0000 UpperCamelCase :Optional[Any] = [1, 6, vocab_size] self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) print(output[:, :3, :3] ) # TODO Replace values below with what was printed above. UpperCamelCase :int = tf.constant( [ [ [-0.1205_3341, -1.026_4901, 0.2922_1946], [-1.513_3783, 0.19_7433, 0.1519_0607], [-5.013_5403, -3.90_0256, -0.8403_8764], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Optional[int] =1E-4 def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :str = tf.constant([[4, 10]] ) UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=6 , embedding_dim=6 ) UpperCamelCase :str = emba(input_ids.shape ) UpperCamelCase :List[str] = tf.constant( [[0.0000, 0.0000, 0.0000, 1.0000, 1.0000, 1.0000], [0.8415, 0.0464, 0.0022, 0.5403, 0.9989, 1.0000]] ) tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Dict = tf.constant( [ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.8415, 0.8219, 0.8020, 0.7819, 0.7617], [0.9093, 0.9364, 0.9581, 0.9749, 0.9870], ] ) UpperCamelCase :Dict = TFRoFormerSinusoidalPositionalEmbedding(num_positions=512 , embedding_dim=512 ) emba([2, 16, 512] ) UpperCamelCase :Any = emba.weight[:3, :5] tf.debugging.assert_near(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) @require_tf class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" UpperCamelCase_ : List[Any] =1E-4 def UpperCAmelCase ( self ) -> List[str]: # 2,12,16,64 UpperCamelCase :List[Any] = tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = -tf.reshape(tf.range(2 * 12 * 16 * 64 , dtype=tf.floataa ) , shape=(2, 12, 16, 64) ) / 100 UpperCamelCase :List[Any] = TFRoFormerSinusoidalPositionalEmbedding(num_positions=32 , embedding_dim=64 ) UpperCamelCase :int = embed_positions([2, 16, 768] )[None, None, :, :] UpperCamelCase , UpperCamelCase :List[str] = TFRoFormerSelfAttention.apply_rotary_position_embeddings( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = tf.constant( [ [0.0000, 0.0100, 0.0200, 0.0300, 0.0400, 0.0500, 0.0600, 0.0700], [-0.2012, 0.8897, 0.0263, 0.9401, 0.2074, 0.9463, 0.3481, 0.9343], [-1.7057, 0.6271, -1.2145, 1.3897, -0.6303, 1.7647, -0.1173, 1.8985], [-2.1731, -1.6397, -2.7358, 0.2854, -2.1840, 1.7183, -1.3018, 2.4871], [0.2717, -3.6173, -2.9206, -2.1988, -3.6638, 0.3858, -2.9155, 2.2980], [3.9859, -2.1580, -0.7984, -4.4904, -4.1181, -2.0252, -4.4782, 1.1253], ] ) UpperCamelCase :Optional[int] = tf.constant( [ [0.0000, -0.0100, -0.0200, -0.0300, -0.0400, -0.0500, -0.0600, -0.0700], [0.2012, -0.8897, -0.0263, -0.9401, -0.2074, -0.9463, -0.3481, -0.9343], [1.7057, -0.6271, 1.2145, -1.3897, 0.6303, -1.7647, 0.1173, -1.8985], [2.1731, 1.6397, 2.7358, -0.2854, 2.1840, -1.7183, 1.3018, -2.4871], [-0.2717, 3.6173, 2.9206, 2.1988, 3.6638, -0.3858, 2.9155, -2.2980], [-3.9859, 2.1580, 0.7984, 4.4904, 4.1181, 2.0252, 4.4782, -1.1253], ] ) tf.debugging.assert_near(query_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance ) tf.debugging.assert_near(key_layer[0, 0, :6, :8] , SCREAMING_SNAKE_CASE_ , atol=self.tolerance )
259
1
# Note: if you intend to run this script make sure you look under scripts/fsmt/ # to locate the appropriate script to do the work correctly. There is a set of scripts to: # - download and prepare data and run the conversion script # - perform eval to get the best hparam into the config # - generate model_cards - useful if you have multiple models from the same paper import argparse import json import os import re from collections import OrderedDict from os.path import basename, dirname import fairseq import torch from fairseq import hub_utils from fairseq.data.dictionary import Dictionary from transformers import FSMTConfig, FSMTForConditionalGeneration from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() __snake_case = 2 # based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping` # values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults: # # * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users) # * `early_stopping`: `False` consistently scored better # * `length_penalty` varied, so will assign the best one depending on the model __snake_case = { # fairseq: """wmt19-ru-en""": {"""length_penalty""": 1.1}, """wmt19-en-ru""": {"""length_penalty""": 1.1_5}, """wmt19-en-de""": {"""length_penalty""": 1.0}, """wmt19-de-en""": {"""length_penalty""": 1.1}, # allenai: """wmt16-en-de-dist-12-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-dist-6-1""": {"""length_penalty""": 0.6}, """wmt16-en-de-12-1""": {"""length_penalty""": 0.8}, """wmt19-de-en-6-6-base""": {"""length_penalty""": 0.6}, """wmt19-de-en-6-6-big""": {"""length_penalty""": 0.6}, } # this remaps the different models to their organization names __snake_case = {} for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: __snake_case = """facebook""" for m in [ "wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1", "wmt19-de-en-6-6-base", "wmt19-de-en-6-6-big", ]: __snake_case = """allenai""" def _A ( SCREAMING_SNAKE_CASE__ : str ): # (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up, # e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7} UpperCamelCase :List[str] = dict((re.sub(R'''@@$''' , '''''' , SCREAMING_SNAKE_CASE__ ), v) if k.endswith('''@@''' ) else (re.sub(R'''$''' , '''</w>''' , SCREAMING_SNAKE_CASE__ ), v) for k, v in d.items() ) UpperCamelCase :List[Any] = '''<s> <pad> </s> <unk>'''.split() # restore the special tokens for k in keep_keys: del da[F'''{k}</w>'''] UpperCamelCase :Any = d[k] # restore return da def _A ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] ): # prep assert os.path.exists(SCREAMING_SNAKE_CASE__ ) os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) print(F'''Writing results to {pytorch_dump_folder_path}''' ) # handle various types of models UpperCamelCase :List[Any] = basename(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :str = dirname(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel UpperCamelCase :List[str] = cls.hub_models() UpperCamelCase :Tuple = {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''} UpperCamelCase :str = '''.''' # note: since the model dump is old, fairseq has upgraded its model some # time later, and it does a whole lot of rewrites and splits on the saved # weights, therefore we can't use torch.load() directly on the model file. # see: upgrade_state_dict(state_dict) in fairseq_model.py print(F'''using checkpoint {checkpoint_file}''' ) UpperCamelCase :Tuple = hub_utils.from_pretrained( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , archive_map=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[Any] = vars(chkpt['''args''']['''model'''] ) UpperCamelCase :List[str] = args['''source_lang'''] UpperCamelCase :Dict = args['''target_lang'''] UpperCamelCase :Optional[Any] = dirname(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Union[str, Any] = basename(SCREAMING_SNAKE_CASE__ ) # dicts UpperCamelCase :Optional[int] = os.path.join(SCREAMING_SNAKE_CASE__ , F'''dict.{src_lang}.txt''' ) UpperCamelCase :Dict = os.path.join(SCREAMING_SNAKE_CASE__ , F'''dict.{tgt_lang}.txt''' ) UpperCamelCase :Tuple = Dictionary.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = rewrite_dict_keys(src_dict.indices ) UpperCamelCase :List[Any] = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab-src.json''' ) print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ , indent=SCREAMING_SNAKE_CASE__ ) ) # detect whether this is a do_lower_case situation, which can be derived by checking whether we # have at least one uppercase letter in the source vocab UpperCamelCase :Optional[Any] = True for k in src_vocab.keys(): if not k.islower(): UpperCamelCase :List[Any] = False break UpperCamelCase :Any = Dictionary.load(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Any = rewrite_dict_keys(tgt_dict.indices ) UpperCamelCase :Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :List[str] = os.path.join(SCREAMING_SNAKE_CASE__ , '''vocab-tgt.json''' ) print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ , indent=SCREAMING_SNAKE_CASE__ ) ) # merges_file (bpecodes) UpperCamelCase :Optional[int] = os.path.join(SCREAMING_SNAKE_CASE__ , VOCAB_FILES_NAMES['''merges_file'''] ) for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code" UpperCamelCase :Dict = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if os.path.exists(SCREAMING_SNAKE_CASE__ ): break with open(SCREAMING_SNAKE_CASE__ , encoding='''utf-8''' ) as fin: UpperCamelCase :str = fin.read() UpperCamelCase :List[str] = re.sub(R''' \d+$''' , '''''' , SCREAMING_SNAKE_CASE__ , 0 , re.M ) # remove frequency number print(F'''Generating {merges_file}''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as fout: fout.write(SCREAMING_SNAKE_CASE__ ) # model config UpperCamelCase :Any = os.path.join(SCREAMING_SNAKE_CASE__ , '''config.json''' ) # validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe - # may have to modify the tokenizer if a different type is used by a future model assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args["bpe"]}''' assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args["tokenizer"]}''' UpperCamelCase :List[Any] = { '''architectures''': ['''FSMTForConditionalGeneration'''], '''model_type''': '''fsmt''', '''activation_dropout''': args['''activation_dropout'''], '''activation_function''': '''relu''', '''attention_dropout''': args['''attention_dropout'''], '''d_model''': args['''decoder_embed_dim'''], '''dropout''': args['''dropout'''], '''init_std''': 0.02, '''max_position_embeddings''': args['''max_source_positions'''], '''num_hidden_layers''': args['''encoder_layers'''], '''src_vocab_size''': src_vocab_size, '''tgt_vocab_size''': tgt_vocab_size, '''langs''': [src_lang, tgt_lang], '''encoder_attention_heads''': args['''encoder_attention_heads'''], '''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''], '''encoder_layerdrop''': args['''encoder_layerdrop'''], '''encoder_layers''': args['''encoder_layers'''], '''decoder_attention_heads''': args['''decoder_attention_heads'''], '''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''], '''decoder_layerdrop''': args['''decoder_layerdrop'''], '''decoder_layers''': args['''decoder_layers'''], '''bos_token_id''': 0, '''pad_token_id''': 1, '''eos_token_id''': 2, '''is_encoder_decoder''': True, '''scale_embedding''': not args['''no_scale_embedding'''], '''tie_word_embeddings''': args['''share_all_embeddings'''], } # good hparam defaults to start with UpperCamelCase :Any = 5 UpperCamelCase :int = False if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]: UpperCamelCase :str = best_score_hparams[model_dir]['''length_penalty'''] else: UpperCamelCase :int = 1.0 print(F'''Generating {fsmt_model_config_file}''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ , indent=SCREAMING_SNAKE_CASE__ ) ) # tokenizer config UpperCamelCase :Dict = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Tuple = { '''langs''': [src_lang, tgt_lang], '''model_max_length''': 1024, '''do_lower_case''': do_lower_case, } print(F'''Generating {fsmt_tokenizer_config_file}''' ) with open(SCREAMING_SNAKE_CASE__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ , indent=SCREAMING_SNAKE_CASE__ ) ) # model UpperCamelCase :Tuple = chkpt['''models'''][0] UpperCamelCase :int = model.state_dict() # rename keys to start with 'model.' UpperCamelCase :Optional[Any] = OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items() ) # remove unneeded keys UpperCamelCase :int = [ '''model.model''', '''model.encoder.version''', '''model.decoder.version''', '''model.encoder_embed_tokens.weight''', '''model.decoder_embed_tokens.weight''', '''model.encoder.embed_positions._float_tensor''', '''model.decoder.embed_positions._float_tensor''', ] for k in ignore_keys: model_state_dict.pop(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Dict = FSMTConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCamelCase :Optional[int] = FSMTForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) # check that it loads ok model_new.load_state_dict(SCREAMING_SNAKE_CASE__ , strict=SCREAMING_SNAKE_CASE__ ) # save UpperCamelCase :Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print(F'''Generating {pytorch_weights_dump_path}''' ) torch.save(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) print('''Conversion is done!''' ) print('''\nLast step is to upload the files to s3''' ) print(F'''cd {data_root}''' ) print(F'''transformers-cli upload {model_dir}''' ) if __name__ == "__main__": __snake_case = argparse.ArgumentParser() # Required parameters parser.add_argument( """--fsmt_checkpoint_path""", default=None, type=str, required=True, help=( """Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,""" """ bpecodes, etc.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) __snake_case = parser.parse_args() convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
259
import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class UpperCAmelCase_ : """simple docstring""" def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=[0, 1, 2, 3] , 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_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=[1, 384, 24, 24] , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=None , ) -> int: UpperCamelCase :List[Any] = parent UpperCamelCase :List[str] = batch_size UpperCamelCase :Optional[Any] = image_size UpperCamelCase :Optional[Any] = patch_size UpperCamelCase :Optional[Any] = num_channels UpperCamelCase :Union[str, Any] = is_training UpperCamelCase :Dict = use_labels UpperCamelCase :List[Any] = hidden_size UpperCamelCase :Optional[int] = num_hidden_layers UpperCamelCase :Any = backbone_out_indices UpperCamelCase :int = num_attention_heads UpperCamelCase :Union[str, Any] = intermediate_size UpperCamelCase :List[str] = hidden_act UpperCamelCase :Optional[int] = hidden_dropout_prob UpperCamelCase :int = attention_probs_dropout_prob UpperCamelCase :Optional[Any] = initializer_range UpperCamelCase :List[Any] = num_labels UpperCamelCase :Any = backbone_featmap_shape UpperCamelCase :Optional[int] = scope UpperCamelCase :Optional[int] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) UpperCamelCase :Tuple = (image_size // patch_size) ** 2 UpperCamelCase :int = num_patches + 1 def UpperCAmelCase ( self ) -> str: UpperCamelCase :Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase :int = None if self.use_labels: UpperCamelCase :str = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) UpperCamelCase :Any = self.get_config() return config, pixel_values, labels def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :Tuple = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [96, 192, 384, 768], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=SCREAMING_SNAKE_CASE_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=SCREAMING_SNAKE_CASE_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: UpperCamelCase :Optional[int] = DPTModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Optional[int] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: UpperCamelCase :Tuple = self.num_labels UpperCamelCase :Any = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :Union[str, Any] = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> Tuple: UpperCamelCase :int = self.num_labels UpperCamelCase :str = DPTForSemanticSegmentation(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase :List[str] = model(SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :List[Any] = self.prepare_config_and_inputs() UpperCamelCase , UpperCamelCase , UpperCamelCase :Optional[Any] = config_and_inputs UpperCamelCase :List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( lowercase, lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : Tuple =(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () UpperCamelCase_ : Optional[Any] =( { 'depth-estimation': DPTForDepthEstimation, 'feature-extraction': DPTModel, 'image-segmentation': DPTForSemanticSegmentation, } if is_torch_available() else {} ) UpperCamelCase_ : List[Any] =False UpperCamelCase_ : Optional[int] =False UpperCamelCase_ : Union[str, Any] =False def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[Any] = DPTModelTester(self ) UpperCamelCase :List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , has_text_modality=SCREAMING_SNAKE_CASE_ , hidden_size=37 ) def UpperCAmelCase ( self ) -> Union[str, Any]: self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def UpperCAmelCase ( self ) -> int: pass def UpperCAmelCase ( self ) -> Optional[int]: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) UpperCamelCase :Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_ , nn.Linear ) ) def UpperCAmelCase ( self ) -> int: UpperCamelCase , UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase :Optional[Any] = model_class(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase :Tuple = [*signature.parameters.keys()] UpperCamelCase :Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Optional[Any]: UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Tuple: UpperCamelCase :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> Any: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :int = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ): continue UpperCamelCase :Union[str, Any] = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.train() UpperCamelCase :Union[str, Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Optional[int]: for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue UpperCamelCase , UpperCamelCase :List[str] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Union[str, Any] = False UpperCamelCase :Dict = True if model_class in get_values(SCREAMING_SNAKE_CASE_ ) or not model_class.supports_gradient_checkpointing: continue UpperCamelCase :Tuple = model_class(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.gradient_checkpointing_enable() model.train() UpperCamelCase :List[Any] = self._prepare_for_class(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , return_labels=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :List[str] = model(**SCREAMING_SNAKE_CASE_ ).loss loss.backward() def UpperCAmelCase ( self ) -> Dict: UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Dict = _config_zero_init(SCREAMING_SNAKE_CASE_ ) for model_class in self.all_model_classes: UpperCamelCase :Tuple = model_class(config=SCREAMING_SNAKE_CASE_ ) # Skip the check for the backbone UpperCamelCase :List[str] = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": UpperCamelCase :Tuple = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def UpperCAmelCase ( self ) -> Tuple: pass @slow def UpperCAmelCase ( self ) -> Any: for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: UpperCamelCase :int = DPTModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) def UpperCAmelCase ( self ) -> List[Any]: # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type UpperCamelCase , UpperCamelCase :int = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase :Optional[Any] = '''add''' with self.assertRaises(SCREAMING_SNAKE_CASE_ ): UpperCamelCase :int = DPTForDepthEstimation(SCREAMING_SNAKE_CASE_ ) def _A ( ): UpperCamelCase :List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> str: UpperCamelCase :Any = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) UpperCamelCase :int = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Any = prepare_img() UpperCamelCase :Union[str, Any] = image_processor(images=SCREAMING_SNAKE_CASE_ , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE_ ) # forward pass with torch.no_grad(): UpperCamelCase :Union[str, Any] = model(**SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = outputs.predicted_depth # verify the predicted depth UpperCamelCase :List[str] = torch.Size((1, 384, 384) ) self.assertEqual(predicted_depth.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase :str = torch.tensor( [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(SCREAMING_SNAKE_CASE_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
259
1