code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
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 _lowercase : str =get_tests_dir('''fixtures/test_sentencepiece.model''') if is_sentencepiece_available(): import sentencepiece as sp _lowercase : int =5 _lowercase : Dict =1_0 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Any = SpeechaTextTokenizer lowercase : Dict = False lowercase : Optional[Any] = True def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: super().setUp() A : Optional[int] =sp.SentencePieceProcessor() spm_model.Load(SCREAMING_SNAKE_CASE__ ) A : List[Any] =['<s>', '<pad>', '</s>', '<unk>'] vocab += [spm_model.IdToPiece(id_ ) for id_ in range(len(SCREAMING_SNAKE_CASE__ ) )] A : Optional[Any] =dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) A : List[str] =Path(self.tmpdirname ) save_json(SCREAMING_SNAKE_CASE__ , save_dir / VOCAB_FILES_NAMES['vocab_file'] ) if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists(): copyfile(SCREAMING_SNAKE_CASE__ , save_dir / VOCAB_FILES_NAMES['spm_file'] ) A : Tuple =SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> int: A : Tuple ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : str =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(SCREAMING_SNAKE_CASE__ ) , 10_01 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: self.assertEqual(self.get_tokenizer().vocab_size , 10_01 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: A : Union[str, Any] =SpeechaTextTokenizer.from_pretrained(self.tmpdirname ) A : int =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [2_89, 50, 14, 1_74, 3_86] , ) A : Dict =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.'] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [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] ) A : Tuple =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: # fmt: off A : str ={'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=SCREAMING_SNAKE_CASE__ , model_name='facebook/s2t-small-mustc-en-de-st' , revision='a14f04cf0776c02f62a8cb800cf7909e15ea23ad' , ) @require_sentencepiece class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : Any = "valhalla/s2t_mustc_multilinguial_medium" lowercase : Tuple = "C'est trop cool" lowercase : Union[str, Any] = "Esto es genial" @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Any ) -> List[Any]: A : SpeechaTextTokenizer =SpeechaTextTokenizer.from_pretrained(cls.checkpoint_name ) return cls def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: 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 SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: self.assertEqual(self.tokenizer.vocab_size , 1_00_00 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: self.assertIn(SCREAMING_SNAKE_CASE__ , self.tokenizer.all_special_ids ) A : Any =[ES_CODE, 4, 16_01, 47, 76_47, 2] A : str =self.tokenizer.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Optional[Any]: A : Tuple ='fr' A : Tuple =self.tokenizer(self.french_text ).input_ids self.assertEqual(encoded[0] , SCREAMING_SNAKE_CASE__ ) self.assertEqual(encoded[-1] , self.tokenizer.eos_token_id ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Any ='fr' self.assertListEqual(self.tokenizer.prefix_tokens , [FR_CODE] ) A : str ='es' self.assertListEqual(self.tokenizer.prefix_tokens , [ES_CODE] )
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
import inspect import unittest from transformers import BitConfig 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_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple=3 , SCREAMING_SNAKE_CASE__ : List[str]=32 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : int=10 , SCREAMING_SNAKE_CASE__ : Optional[int]=[8, 16, 32, 64] , SCREAMING_SNAKE_CASE__ : int=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="relu" , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Dict=["stage2", "stage3", "stage4"] , SCREAMING_SNAKE_CASE__ : List[str]=[2, 3, 4] , SCREAMING_SNAKE_CASE__ : List[str]=1 , ) -> Union[str, Any]: A : Tuple =parent A : List[Any] =batch_size A : Any =image_size A : int =num_channels A : str =embeddings_size A : Any =hidden_sizes A : Dict =depths A : Optional[int] =is_training A : Any =use_labels A : Optional[Any] =hidden_act A : Optional[Any] =num_labels A : Optional[Any] =scope A : str =len(SCREAMING_SNAKE_CASE__ ) A : Any =out_features A : List[Any] =out_indices A : Dict =num_groups def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[Any]: A : Tuple =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A : List[Any] =None if self.use_labels: A : str =ids_tensor([self.batch_size] , self.num_labels ) A : List[str] =self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE_ ( self : Any ) -> int: return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Any: A : Any =BitModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : int =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: A : List[Any] =self.num_labels A : List[str] =BitForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : Any =model(SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: A : Any =BitBackbone(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : Any =model(SCREAMING_SNAKE_CASE__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None A : Any =None A : int =BitBackbone(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() A : Dict =model(SCREAMING_SNAKE_CASE__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: A : Optional[Any] =self.prepare_config_and_inputs() A , A , A : Tuple =config_and_inputs A : Optional[Any] ={'pixel_values': pixel_values} return config, inputs_dict @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Dict = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowercase : Union[str, Any] = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) lowercase : str = False lowercase : List[Any] = False lowercase : List[str] = False lowercase : str = False lowercase : str = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : List[str] =BitModelTester(self ) A : Tuple =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: return @unittest.skip(reason='Bit does not output attentions' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[Any]: pass @unittest.skip(reason='Bit does not use inputs_embeds' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: pass @unittest.skip(reason='Bit does not support input and output embeddings' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[str]: pass def SCREAMING_SNAKE_CASE_ ( self : str ) -> int: A , A : Optional[Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : int =model_class(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A : str =[*signature.parameters.keys()] A : List[Any] =['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : Union[str, Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Dict =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[Any]: A , A : Any =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A : str =model_class(config=SCREAMING_SNAKE_CASE__ ) for name, module in model.named_modules(): if isinstance(SCREAMING_SNAKE_CASE__ , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f'Parameter {name} of model {model_class} seems not properly initialized' , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[Any]: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : int ): A : Union[str, Any] =model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): A : Tuple =model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) A : List[str] =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states A : Dict =self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) A , A : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() A : Union[str, Any] =['preactivation', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: A : str =layer_type A : Union[str, Any] =True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A : Union[str, Any] =True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='Bit does not use feedforward chunking' ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Dict: pass def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Dict: A : List[Any] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A : str =BitModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def A__ ( ) -> List[str]: A : Any =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @cached_property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[Any]: return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict: A : int =BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =self.default_image_processor A : str =prepare_img() A : List[Any] =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): A : Tuple =model(**SCREAMING_SNAKE_CASE__ ) # verify the logits A : List[str] =torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([[-0.6_5_2_6, -0.5_2_6_3, -1.4_3_9_8]] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : int = (BitBackbone,) if is_torch_available() else () lowercase : Dict = BitConfig lowercase : Dict = False def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: A : Any =BitModelTester(self )
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsรฉ.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
from string import ascii_uppercase _lowercase : str ={char: i for i, char in enumerate(ascii_uppercase)} _lowercase : List[Any] =dict(enumerate(ascii_uppercase)) def A__ ( lowercase: str, lowercase: str ) -> str: A : Optional[Any] =len(lowercase ) A : int =0 while True: if x == i: A : Optional[int] =0 if len(lowercase ) == len(lowercase ): break key += key[i] i += 1 return key def A__ ( lowercase: str, lowercase: str ) -> str: A : List[str] ='' A : str =0 for letter in message: if letter == " ": cipher_text += " " else: A : Optional[int] =(dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def A__ ( lowercase: str, lowercase: str ) -> str: A : Tuple ='' A : List[str] =0 for letter in cipher_text: if letter == " ": or_txt += " " else: A : Optional[int] =(dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def A__ ( ) -> None: A : str ='THE GERMAN ATTACK' A : Optional[int] ='SECRET' A : Optional[int] =generate_key(lowercase, lowercase ) A : List[Any] =cipher_text(lowercase, lowercase ) print(F'Encrypted Text = {s}' ) print(F'Original Text = {original_text(lowercase, lowercase )}' ) if __name__ == "__main__": import doctest doctest.testmod() main()
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase : Any =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = "deit" def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any]=7_68 , SCREAMING_SNAKE_CASE__ : str=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : Optional[int]=30_72 , SCREAMING_SNAKE_CASE__ : Optional[int]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Any=0.0_2 , SCREAMING_SNAKE_CASE__ : Any=1e-12 , SCREAMING_SNAKE_CASE__ : str=2_24 , SCREAMING_SNAKE_CASE__ : Any=16 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : List[Any]=16 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> Union[str, Any]: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : int =hidden_size A : Tuple =num_hidden_layers A : Dict =num_attention_heads A : Dict =intermediate_size A : Any =hidden_act A : Tuple =hidden_dropout_prob A : int =attention_probs_dropout_prob A : Dict =initializer_range A : int =layer_norm_eps A : int =image_size A : Tuple =patch_size A : str =num_channels A : str =qkv_bias A : Optional[Any] =encoder_stride class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Dict = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> float: return 1e-4
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import List import timm import torch import torch.nn as nn from huggingface_hub import hf_hub_download from torch import Tensor from transformers import AutoImageProcessor, ResNetConfig, ResNetForImageClassification from transformers.utils import logging logging.set_verbosity_info() _lowercase : Optional[int] =logging.get_logger() @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : nn.Module lowercase : List[nn.Module] = field(default_factory=lowerCAmelCase_ ) lowercase : list = field(default_factory=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tensor , SCREAMING_SNAKE_CASE__ : Tensor ) -> List[Any]: A : Optional[Any] =len(list(m.modules() ) ) == 1 or isinstance(SCREAMING_SNAKE_CASE__ , nn.Convad ) or isinstance(SCREAMING_SNAKE_CASE__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(SCREAMING_SNAKE_CASE__ ) def __call__( self : Any , SCREAMING_SNAKE_CASE__ : Tensor ) -> Dict: for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(SCREAMING_SNAKE_CASE__ ) [x.remove() for x in self.handles] return self @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Union[str, Any]: # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda SCREAMING_SNAKE_CASE__ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : nn.Module lowercase : nn.Module lowercase : int = 0 lowercase : List = field(default_factory=lowerCAmelCase_ ) lowercase : List = field(default_factory=lowerCAmelCase_ ) def __call__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tensor ) -> str: A : Tuple =Tracker(self.dest )(SCREAMING_SNAKE_CASE__ ).parametrized A : int =Tracker(self.src )(SCREAMING_SNAKE_CASE__ ).parametrized A : List[Any] =list(filter(lambda SCREAMING_SNAKE_CASE__ : type(SCREAMING_SNAKE_CASE__ ) not in self.src_skip , SCREAMING_SNAKE_CASE__ ) ) A : int =list(filter(lambda SCREAMING_SNAKE_CASE__ : type(SCREAMING_SNAKE_CASE__ ) not in self.dest_skip , SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) != len(SCREAMING_SNAKE_CASE__ ): raise Exception( f'Numbers of operations are different. Source module has {len(SCREAMING_SNAKE_CASE__ )} operations while' f' destination module has {len(SCREAMING_SNAKE_CASE__ )}.' ) for dest_m, src_m in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(f'Transfered from={src_m} to={dest_m}' ) def A__ ( lowercase: str, lowercase: ResNetConfig, lowercase: Path, lowercase: bool = True ) -> Optional[int]: print(F'Converting {name}...' ) with torch.no_grad(): A : Dict =timm.create_model(lowercase, pretrained=lowercase ).eval() A : Any =ResNetForImageClassification(lowercase ).eval() A : Dict =ModuleTransfer(src=lowercase, dest=lowercase ) A : Optional[int] =torch.randn((1, 3, 224, 224) ) module_transfer(lowercase ) assert torch.allclose(from_model(lowercase ), our_model(lowercase ).logits ), "The model logits don't match the original one." A : int =F'resnet{"-".join(name.split("resnet" ) )}' print(lowercase ) if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add model', use_temp_dir=lowercase, ) # we can use the convnext one A : Union[str, Any] =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) image_processor.push_to_hub( repo_path_or_name=save_directory / checkpoint_name, commit_message='Add image processor', use_temp_dir=lowercase, ) print(F'Pushed {checkpoint_name}' ) def A__ ( lowercase: Path, lowercase: str = None, lowercase: bool = True ) -> Any: A : Optional[int] ='imagenet-1k-id2label.json' A : str =1_000 A : Optional[Any] =(1, num_labels) A : Dict ='huggingface/label-files' A : int =num_labels A : str =json.load(open(hf_hub_download(lowercase, lowercase, repo_type='dataset' ), 'r' ) ) A : Dict ={int(lowercase ): v for k, v in idalabel.items()} A : List[Any] =idalabel A : int ={v: k for k, v in idalabel.items()} A : Union[str, Any] =partial(lowercase, num_labels=lowercase, idalabel=lowercase, labelaid=lowercase ) A : List[Any] ={ 'resnet18': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet26': ImageNetPreTrainedConfig( depths=[2, 2, 2, 2], hidden_sizes=[256, 512, 1_024, 2_048], layer_type='bottleneck' ), 'resnet34': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[64, 128, 256, 512], layer_type='basic' ), 'resnet50': ImageNetPreTrainedConfig( depths=[3, 4, 6, 3], hidden_sizes=[256, 512, 1_024, 2_048], layer_type='bottleneck' ), 'resnet101': ImageNetPreTrainedConfig( depths=[3, 4, 23, 3], hidden_sizes=[256, 512, 1_024, 2_048], layer_type='bottleneck' ), 'resnet152': ImageNetPreTrainedConfig( depths=[3, 8, 36, 3], hidden_sizes=[256, 512, 1_024, 2_048], layer_type='bottleneck' ), } if model_name: convert_weight_and_push(lowercase, names_to_config[model_name], lowercase, lowercase ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(lowercase, lowercase, lowercase, lowercase ) return config, expected_shape if __name__ == "__main__": _lowercase : str =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help=( '''The name of the model you wish to convert, it must be one of the supported resnet* architecture,''' ''' currently: resnet18,26,34,50,101,152. If `None`, all of them will the converted.''' ), ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=Path, required=True, help='''Path to the output PyTorch model directory.''', ) parser.add_argument( '''--push_to_hub''', default=True, type=bool, required=False, help='''If True, push model and image processor to the hub.''', ) _lowercase : List[str] =parser.parse_args() _lowercase : Path =args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'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. A : Optional[int] =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: A : str =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) 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 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =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: A : Optional[Any] =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) 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 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).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!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =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] ) ): A : Tuple ='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 A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\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()
661
1
def A__ ( lowercase: int ) -> bool: if p < 2: raise ValueError('p should not be less than 2!' ) elif p == 2: return True A : int =4 A : List[Any] =(1 << p) - 1 for _ in range(p - 2 ): A : Optional[int] =((s * s) - 2) % m return s == 0 if __name__ == "__main__": print(lucas_lehmer_test(7)) print(lucas_lehmer_test(1_1))
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
import os import torch from ..logging import get_logger from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME from .versions import is_torch_version if is_torch_version('''>=''', FSDP_PYTORCH_VERSION): import torch.distributed.checkpoint as dist_cp from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType _lowercase : Union[str, Any] =get_logger(__name__) def A__ ( lowercase: int, lowercase: str, lowercase: Union[str, Any], lowercase: Optional[int], lowercase: Optional[int]=0 ) -> Optional[int]: os.makedirs(lowercase, exist_ok=lowercase ) with FSDP.state_dict_type( lowercase, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): A : List[Any] =model.state_dict() if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A : Optional[int] =F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A : Union[str, Any] =os.path.join(lowercase, lowercase ) if accelerator.process_index == 0: logger.info(F'Saving model to {output_model_file}' ) torch.save(lowercase, lowercase ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A : Tuple =( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A : Dict =os.path.join(lowercase, lowercase ) logger.info(F'Saving model to {output_model_file}' ) torch.save(lowercase, lowercase ) logger.info(F'Model saved to {output_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A : List[str] =os.path.join(lowercase, F'{MODEL_NAME}_{model_index}' ) os.makedirs(lowercase, exist_ok=lowercase ) logger.info(F'Saving model to {ckpt_dir}' ) A : Optional[int] ={'model': state_dict} dist_cp.save_state_dict( state_dict=lowercase, storage_writer=dist_cp.FileSystemWriter(lowercase ), planner=DefaultSavePlanner(), ) logger.info(F'Model saved to {ckpt_dir}' ) def A__ ( lowercase: Optional[int], lowercase: Dict, lowercase: Dict, lowercase: Optional[int], lowercase: Any=0 ) -> List[Any]: accelerator.wait_for_everyone() with FSDP.state_dict_type( lowercase, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if type(lowercase ) != FSDP and accelerator.process_index != 0: if not fsdp_plugin.sync_module_states: raise ValueError( 'Set the `sync_module_states` flag to `True` so that model states are synced across processes when ' 'initializing FSDP object' ) return A : List[str] =F'{MODEL_NAME}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}.bin' A : Dict =os.path.join(lowercase, lowercase ) logger.info(F'Loading model from {input_model_file}' ) A : Optional[Any] =torch.load(lowercase ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: A : Dict =( F'{MODEL_NAME}_rank{accelerator.process_index}.bin' if model_index == 0 else F'{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin' ) A : Optional[Any] =os.path.join(lowercase, lowercase ) logger.info(F'Loading model from {input_model_file}' ) A : int =torch.load(lowercase ) logger.info(F'Model loaded from {input_model_file}' ) elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: A : List[str] =( os.path.join(lowercase, F'{MODEL_NAME}_{model_index}' ) if F'{MODEL_NAME}' not in input_dir else input_dir ) logger.info(F'Loading model from {ckpt_dir}' ) A : Optional[Any] ={'model': model.state_dict()} dist_cp.load_state_dict( state_dict=lowercase, storage_reader=dist_cp.FileSystemReader(lowercase ), planner=DefaultLoadPlanner(), ) A : Optional[Any] =state_dict['model'] logger.info(F'Model loaded from {ckpt_dir}' ) model.load_state_dict(lowercase ) def A__ ( lowercase: Any, lowercase: str, lowercase: str, lowercase: Optional[Any], lowercase: int, lowercase: List[str]=0 ) -> Optional[int]: os.makedirs(lowercase, exist_ok=lowercase ) with FSDP.state_dict_type( lowercase, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): A : Union[str, Any] =FSDP.optim_state_dict(lowercase, lowercase ) if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: if accelerator.process_index == 0: A : int =( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A : Union[str, Any] =os.path.join(lowercase, lowercase ) logger.info(F'Saving Optimizer state to {output_optimizer_file}' ) torch.save(lowercase, lowercase ) logger.info(F'Optimizer state saved in {output_optimizer_file}' ) else: A : int =os.path.join(lowercase, F'{OPTIMIZER_NAME}_{optimizer_index}' ) os.makedirs(lowercase, exist_ok=lowercase ) logger.info(F'Saving Optimizer state to {ckpt_dir}' ) dist_cp.save_state_dict( state_dict={'optimizer': optim_state}, storage_writer=dist_cp.FileSystemWriter(lowercase ), planner=DefaultSavePlanner(), ) logger.info(F'Optimizer state saved in {ckpt_dir}' ) def A__ ( lowercase: Tuple, lowercase: int, lowercase: int, lowercase: Optional[int], lowercase: Union[str, Any], lowercase: Optional[Any]=0 ) -> int: accelerator.wait_for_everyone() with FSDP.state_dict_type( lowercase, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config ): if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: A : Any =None # below check should work but currently it isn't working (mostly opytorch issue), # in the meantime disabling it at the cost of excess memory usage # if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: A : Optional[Any] =( F'{OPTIMIZER_NAME}.bin' if optimizer_index == 0 else F'{OPTIMIZER_NAME}_{optimizer_index}.bin' ) A : Union[str, Any] =os.path.join(lowercase, lowercase ) logger.info(F'Loading Optimizer state from {input_optimizer_file}' ) A : Tuple =torch.load(lowercase ) logger.info(F'Optimizer state loaded from {input_optimizer_file}' ) else: A : Optional[Any] =( os.path.join(lowercase, F'{OPTIMIZER_NAME}_{optimizer_index}' ) if F'{OPTIMIZER_NAME}' not in input_dir else input_dir ) logger.info(F'Loading Optimizer from {ckpt_dir}' ) A : Tuple =load_sharded_optimizer_state_dict( model_state_dict=model.state_dict(), optimizer_key='optimizer', storage_reader=dist_cp.FileSystemReader(lowercase ), ) A : Optional[Any] =optim_state['optimizer'] logger.info(F'Optimizer loaded from {ckpt_dir}' ) A : Tuple =FSDP.optim_state_dict_to_load(lowercase, lowercase, lowercase ) optimizer.load_state_dict(lowercase )
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
_lowercase : Any ='''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def A__ ( ) -> None: A : Dict =input('Enter message: ' ) A : Union[str, Any] =input('Enter key [alphanumeric]: ' ) A : Any =input('Encrypt/Decrypt [e/d]: ' ) if mode.lower().startswith('e' ): A : List[str] ='encrypt' A : str =encrypt_message(lowercase, lowercase ) elif mode.lower().startswith('d' ): A : List[Any] ='decrypt' A : Optional[Any] =decrypt_message(lowercase, lowercase ) print(F'\n{mode.title()}ed message:' ) print(lowercase ) def A__ ( lowercase: str, lowercase: str ) -> str: return translate_message(lowercase, lowercase, 'encrypt' ) def A__ ( lowercase: str, lowercase: str ) -> str: return translate_message(lowercase, lowercase, 'decrypt' ) def A__ ( lowercase: str, lowercase: str, lowercase: str ) -> str: A : str =[] A : Dict =0 A : List[str] =key.upper() for symbol in message: A : List[Any] =LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(lowercase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(lowercase ): A : Union[str, Any] =0 else: translated.append(lowercase ) return "".join(lowercase ) if __name__ == "__main__": main()
661
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Any =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : Union[str, "sqlalchemy.sql.Selectable"] , SCREAMING_SNAKE_CASE__ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , **SCREAMING_SNAKE_CASE__ : str , ) -> Any: super().__init__(features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =Sql( cache_dir=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , sql=SCREAMING_SNAKE_CASE__ , con=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: A : str =None A : List[Any] =None A : int =None A : List[Any] =None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , ) # Build dataset for splits A : List[Any] =self.builder.as_dataset( split='train' , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dataset , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ) -> str: if num_proc is not None and num_proc <= 0: raise ValueError(f'num_proc {num_proc} must be an integer > 0.' ) A : int =dataset A : int =name A : List[str] =con A : Any =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE A : int =num_proc A : Union[str, Any] =to_sql_kwargs def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> int: A : str =self.to_sql_kwargs.pop('sql' , SCREAMING_SNAKE_CASE__ ) A : Optional[int] =self.to_sql_kwargs.pop('con' , SCREAMING_SNAKE_CASE__ ) A : Dict =self.to_sql_kwargs.pop('index' , SCREAMING_SNAKE_CASE__ ) A : List[Any] =self._write(index=SCREAMING_SNAKE_CASE__ , **self.to_sql_kwargs ) return written def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: A , A , A : Dict =args A : Any ={**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs A : str =query_table( table=self.dataset.data , key=slice(SCREAMING_SNAKE_CASE__ , offset + self.batch_size ) , indices=self.dataset._indices , ) A : Dict =batch.to_pandas() A : List[Any] =df.to_sql(self.name , self.con , index=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return num_rows or len(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: A : Tuple =0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: A , A : Tuple =len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='ba' , disable=not logging.is_progress_bar_enabled() , desc='Creating SQL from Arrow format' , ): written += num_rows return written
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
from math import factorial, radians def A__ ( lowercase: float, lowercase: int = 18, lowercase: int = 10 ) -> float: A : int =angle_in_degrees - ((angle_in_degrees // 3_60.0) * 3_60.0) # Converting from degrees to radians A : List[str] =radians(lowercase ) A : Tuple =angle_in_radians A : Any =3 A : Optional[Any] =-1 for _ in range(lowercase ): result += (b * (angle_in_radians**a)) / factorial(lowercase ) A : str =-b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase, lowercase ) if __name__ == "__main__": __import__('''doctest''').testmod()
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import GLPNImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any]=7 , SCREAMING_SNAKE_CASE__ : List[Any]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=18 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30 , SCREAMING_SNAKE_CASE__ : Dict=4_00 , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Tuple=32 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , ) -> Tuple: A : List[Any] =parent A : List[str] =batch_size A : str =num_channels A : Optional[int] =image_size A : List[Any] =min_resolution A : Optional[Any] =max_resolution A : int =do_resize A : Optional[Any] =size_divisor A : Tuple =do_rescale def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Tuple: return { "do_resize": self.do_resize, "size_divisor": self.size_divisor, "do_rescale": self.do_rescale, } @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Dict = GLPNImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: A : List[str] =GLPNImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : Dict =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size_divisor' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'resample' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_rescale' ) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: pass def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: # Initialize image_processing A : Dict =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Optional[Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input (GLPNImageProcessor doesn't support batching) A : Optional[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: # Initialize image_processing A : List[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : Union[str, Any] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input (GLPNImageProcessor doesn't support batching) A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: # Initialize image_processing A : Tuple =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Optional[int] =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input (GLPNImageProcessor doesn't support batching) A : Dict =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 ) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : int = ["keras_nlp"] def __init__( self : int , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> List[Any]: requires_backends(self , ['keras_nlp'] )
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
import torch from diffusers import DiffusionPipeline class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: super().__init__() self.register_modules(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) def __call__( self : Any ) -> Any: A : Dict =torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) A : Any =1 A : Dict =self.unet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).sample A : List[Any] =self.scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample A : List[str] =scheduler_output - scheduler_output + torch.ones_like(SCREAMING_SNAKE_CASE__ ) return result
661
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 SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
_lowercase : List[Any] ={ '''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''': '''--..''', '''1''': '''.----''', '''2''': '''..---''', '''3''': '''...--''', '''4''': '''....-''', '''5''': '''.....''', '''6''': '''-....''', '''7''': '''--...''', '''8''': '''---..''', '''9''': '''----.''', '''0''': '''-----''', '''&''': '''.-...''', '''@''': '''.--.-.''', ''':''': '''---...''', ''',''': '''--..--''', '''.''': '''.-.-.-''', '''\'''': '''.----.''', '''"''': '''.-..-.''', '''?''': '''..--..''', '''/''': '''-..-.''', '''=''': '''-...-''', '''+''': '''.-.-.''', '''-''': '''-....-''', '''(''': '''-.--.''', ''')''': '''-.--.-''', '''!''': '''-.-.--''', ''' ''': '''/''' } # Exclamation mark is not in ITU-R recommendation # fmt: on _lowercase : List[Any] ={value: key for key, value in MORSE_CODE_DICT.items()} def A__ ( lowercase: str ) -> str: return " ".join(MORSE_CODE_DICT[char] for char in message.upper() ) def A__ ( lowercase: str ) -> str: return "".join(REVERSE_DICT[char] for char in message.split() ) def A__ ( ) -> None: A : List[Any] ='Morse code here!' print(lowercase ) A : Optional[int] =encrypt(lowercase ) print(lowercase ) A : Optional[int] =decrypt(lowercase ) print(lowercase ) if __name__ == "__main__": main()
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''๐Ÿค— Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_electra import ElectraTokenizer _lowercase : Tuple ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowercase : List[str] ={ '''vocab_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/vocab.txt''' ), '''google/electra-base-generator''': '''https://huggingface.co/google/electra-base-generator/resolve/main/vocab.txt''', '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/vocab.txt''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/vocab.txt''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/vocab.txt''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''google/electra-small-generator''': ( '''https://huggingface.co/google/electra-small-generator/resolve/main/tokenizer.json''' ), '''google/electra-base-generator''': ( '''https://huggingface.co/google/electra-base-generator/resolve/main/tokenizer.json''' ), '''google/electra-large-generator''': ( '''https://huggingface.co/google/electra-large-generator/resolve/main/tokenizer.json''' ), '''google/electra-small-discriminator''': ( '''https://huggingface.co/google/electra-small-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-base-discriminator''': ( '''https://huggingface.co/google/electra-base-discriminator/resolve/main/tokenizer.json''' ), '''google/electra-large-discriminator''': ( '''https://huggingface.co/google/electra-large-discriminator/resolve/main/tokenizer.json''' ), }, } _lowercase : int ={ '''google/electra-small-generator''': 5_1_2, '''google/electra-base-generator''': 5_1_2, '''google/electra-large-generator''': 5_1_2, '''google/electra-small-discriminator''': 5_1_2, '''google/electra-base-discriminator''': 5_1_2, '''google/electra-large-discriminator''': 5_1_2, } _lowercase : Tuple ={ '''google/electra-small-generator''': {'''do_lower_case''': True}, '''google/electra-base-generator''': {'''do_lower_case''': True}, '''google/electra-large-generator''': {'''do_lower_case''': True}, '''google/electra-small-discriminator''': {'''do_lower_case''': True}, '''google/electra-base-discriminator''': {'''do_lower_case''': True}, '''google/electra-large-discriminator''': {'''do_lower_case''': True}, } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = VOCAB_FILES_NAMES lowercase : List[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : Dict = PRETRAINED_INIT_CONFIGURATION lowercase : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : List[Any] = ElectraTokenizer def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : List[str]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[UNK]" , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : int="[PAD]" , SCREAMING_SNAKE_CASE__ : Dict="[CLS]" , SCREAMING_SNAKE_CASE__ : str="[MASK]" , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Any=None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Tuple: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) A : Optional[Any] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): A : Union[str, Any] =getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('type' ) ) A : Any =do_lower_case A : Any =strip_accents A : int =tokenize_chinese_chars A : Tuple =normalizer_class(**SCREAMING_SNAKE_CASE__ ) A : Tuple =do_lower_case def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Any=None ) -> Tuple: A : int =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: A : List[str] =[self.sep_token_id] A : int =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: A : Dict =self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() _lowercase : Union[str, Any] =logging.get_logger(__name__) def A__ ( lowercase: List[Any], lowercase: Tuple=False ) -> str: A : Union[str, Any] =[] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'vit.embeddings.cls_token'), ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" A : List[Any] =[(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) return rename_keys def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Union[str, Any]=False ) -> Optional[int]: for i in range(config.num_hidden_layers ): if base_model: A : Optional[Any] ='' else: A : str ='vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A : Dict =state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) A : str =state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A : Optional[Any] =in_proj_weight[ : config.hidden_size, : ] A : str =in_proj_bias[: config.hidden_size] A : List[str] =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A : Dict =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A : Dict =in_proj_weight[ -config.hidden_size :, : ] A : Any =in_proj_bias[-config.hidden_size :] def A__ ( lowercase: Tuple ) -> Tuple: A : List[str] =['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase, lowercase ) def A__ ( lowercase: Optional[int], lowercase: Optional[Any], lowercase: str ) -> Any: A : str =dct.pop(lowercase ) A : Tuple =val def A__ ( ) -> Optional[Any]: A : int ='http://images.cocodataset.org/val2017/000000039769.jpg' A : List[str] =Image.open(requests.get(lowercase, stream=lowercase ).raw ) return im @torch.no_grad() def A__ ( lowercase: str, lowercase: Union[str, Any], lowercase: Optional[int]=True ) -> Dict: A : Any =ViTConfig() # patch_size if model_name[-1] == "8": A : List[str] =8 # set labels if required if not base_model: A : Optional[int] =1_000 A : Optional[Any] ='huggingface/label-files' A : Dict ='imagenet-1k-id2label.json' A : int =json.load(open(hf_hub_download(lowercase, lowercase, repo_type='dataset' ), 'r' ) ) A : List[str] ={int(lowercase ): v for k, v in idalabel.items()} A : Optional[int] =idalabel A : Union[str, Any] ={v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: A : str =384 A : List[Any] =1_536 A : Tuple =12 A : List[str] =6 # load original model from torch hub A : List[str] =torch.hub.load('facebookresearch/dino:main', lowercase ) original_model.eval() # load state_dict of original model, remove and rename some keys A : int =original_model.state_dict() if base_model: remove_classification_head_(lowercase ) A : Dict =create_rename_keys(lowercase, base_model=lowercase ) for src, dest in rename_keys: rename_key(lowercase, lowercase, lowercase ) read_in_q_k_v(lowercase, lowercase, lowercase ) # load HuggingFace model if base_model: A : List[str] =ViTModel(lowercase, add_pooling_layer=lowercase ).eval() else: A : Dict =ViTForImageClassification(lowercase ).eval() model.load_state_dict(lowercase ) # Check outputs on an image, prepared by ViTImageProcessor A : Optional[Any] =ViTImageProcessor() A : str =image_processor(images=prepare_img(), return_tensors='pt' ) A : Tuple =encoding['pixel_values'] A : Optional[Any] =model(lowercase ) if base_model: A : Dict =original_model(lowercase ) assert torch.allclose(lowercase, outputs.last_hidden_state[:, 0, :], atol=1e-1 ) else: A : int =original_model(lowercase ) assert logits.shape == outputs.logits.shape assert torch.allclose(lowercase, outputs.logits, atol=1e-3 ) Path(lowercase ).mkdir(exist_ok=lowercase ) print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowercase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowercase ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''dino_vitb16''', type=str, help='''Name of the model trained with DINO you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--base_model''', action='''store_true''', help='''Whether to only convert the base model (no projection head weights).''', ) parser.set_defaults(base_model=True) _lowercase : List[Any] =parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
from __future__ import annotations from collections.abc import Callable from typing import Any, Generic, TypeVar _lowercase : List[str] =TypeVar('''T''') class SCREAMING_SNAKE_CASE_ ( Generic[T] ): '''simple docstring''' def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : list[T] , SCREAMING_SNAKE_CASE__ : Callable[[T, T], T] ) -> None: A : Any | T =None A : int =len(SCREAMING_SNAKE_CASE__ ) A : list[T] =[any_type for _ in range(self.N )] + arr A : List[Any] =fnc self.build() def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> None: for p in range(self.N - 1 , 0 , -1 ): A : Optional[Any] =self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : T ) -> None: p += self.N A : Tuple =v while p > 1: A : int =p // 2 A : Tuple =self.fn(self.st[p * 2] , self.st[p * 2 + 1] ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> T | None: # noqa: E741 A , A : List[Any] =l + self.N, r + self.N A : T | None =None while l <= r: if l % 2 == 1: A : Tuple =self.st[l] if res is None else self.fn(SCREAMING_SNAKE_CASE__ , self.st[l] ) if r % 2 == 0: A : List[Any] =self.st[r] if res is None else self.fn(SCREAMING_SNAKE_CASE__ , self.st[r] ) A , A : Optional[int] =(l + 1) // 2, (r - 1) // 2 return res if __name__ == "__main__": from functools import reduce _lowercase : Dict =[1, 1_0, -2, 9, -3, 8, 4, -7, 5, 6, 1_1, -1_2] _lowercase : Optional[int] ={ 0: 7, 1: 2, 2: 6, 3: -1_4, 4: 5, 5: 4, 6: 7, 7: -1_0, 8: 9, 9: 1_0, 1_0: 1_2, 1_1: 1, } _lowercase : int =SegmentTree(test_array, min) _lowercase : Optional[int] =SegmentTree(test_array, max) _lowercase : Optional[int] =SegmentTree(test_array, lambda a, b: a + b) def A__ ( ) -> None: for i in range(len(lowercase ) ): for j in range(lowercase, len(lowercase ) ): A : Optional[Any] =reduce(lowercase, test_array[i : j + 1] ) A : Tuple =reduce(lowercase, test_array[i : j + 1] ) A : Dict =reduce(lambda lowercase, lowercase : a + b, test_array[i : j + 1] ) assert min_range == min_segment_tree.query(lowercase, lowercase ) assert max_range == max_segment_tree.query(lowercase, lowercase ) assert sum_range == sum_segment_tree.query(lowercase, lowercase ) test_all_segments() for index, value in test_updates.items(): _lowercase : Optional[int] =value min_segment_tree.update(index, value) max_segment_tree.update(index, value) sum_segment_tree.update(index, value) test_all_segments()
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer _lowercase : Optional[int] =['''bert-base-uncased''', '''bert-base-cased'''] _lowercase : Any ='''hf-internal-testing/tiny-bert-tf-only''' if is_tf_available(): class SCREAMING_SNAKE_CASE_ ( tf.keras.Model ): '''simple docstring''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: super().__init__() A : Optional[Any] =tokenizer A : Any =AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : int =TFAutoModel.from_config(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: A : List[str] =self.tokenizer(SCREAMING_SNAKE_CASE__ ) A : Tuple =self.bert(**SCREAMING_SNAKE_CASE__ ) return out["pooler_output"] @require_tf @require_tensorflow_text class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: super().setUp() A : List[Any] =[ BertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false A : Dict =[TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ , use_fast_bert_tokenizer=SCREAMING_SNAKE_CASE__ ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) A : Union[str, Any] =[ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: ไธ€ ไบŒ ไธ‰ ไธ€ไบŒไธ‰', 'And some much more rare Chinese: ้ฝ‰ ๅ ƒ ้ฝ‰ๅ ƒ', 'Je vais aussi รฉcrire en franรงais pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaฤ‹, ๊ผ', ] A : str =list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[Any]: for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): A : Union[str, Any] =tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='tf' , padding='longest' ) A : Dict =tf_tokenizer(SCREAMING_SNAKE_CASE__ ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: for tf_tokenizer in self.tf_tokenizers: A : List[str] =tf_tokenizer(self.paired_sentences ) A : Tuple =tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : int ) -> str: for tf_tokenizer in self.tf_tokenizers: A : Union[str, Any] =tf.function(SCREAMING_SNAKE_CASE__ ) for test_inputs in (self.test_sentences, self.paired_sentences): A : Union[str, Any] =tf.constant(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =compiled_tokenizer(SCREAMING_SNAKE_CASE__ ) A : int =tf_tokenizer(SCREAMING_SNAKE_CASE__ ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: for tf_tokenizer in self.tf_tokenizers: A : Tuple =ModelToSave(tokenizer=SCREAMING_SNAKE_CASE__ ) A : List[str] =tf.convert_to_tensor(self.test_sentences ) A : Union[str, Any] =model(SCREAMING_SNAKE_CASE__ ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: A : int =Path(SCREAMING_SNAKE_CASE__ ) / 'saved.model' model.save(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tf.keras.models.load_model(SCREAMING_SNAKE_CASE__ ) A : List[Any] =loaded_model(SCREAMING_SNAKE_CASE__ ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
def A__ ( lowercase: Optional[int] ) -> Dict: A : Tuple =[] A : Any =[] A : Optional[int] ={ '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator A : Any =len(lowercase ) if (len(lowercase ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ), 'Stack'.center(lowercase ), 'Postfix'.center(lowercase ), sep=' | ', ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(lowercase ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(lowercase ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(lowercase ) == 0: stack.append(lowercase ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(lowercase ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(lowercase ) # push x to stack print( x.center(8 ), (''.join(lowercase )).ljust(lowercase ), (''.join(lowercase )).ljust(lowercase ), sep=' | ', ) # Output in tabular format while len(lowercase ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ), (''.join(lowercase )).ljust(lowercase ), (''.join(lowercase )).ljust(lowercase ), sep=' | ', ) # Output in tabular format return "".join(lowercase ) # return Postfix as str def A__ ( lowercase: Any ) -> Any: A : int =list(infix[::-1] ) # reverse the infix equation for i in range(len(lowercase ) ): if infix[i] == "(": A : Tuple =')' # change "(" to ")" elif infix[i] == ")": A : Dict ='(' # change ")" to "(" return (infix_2_postfix(''.join(lowercase ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": _lowercase : Tuple =input('''\nEnter an Infix Equation = ''') # Input an Infix equation _lowercase : List[Any] =''''''.join(Infix.split()) # Remove spaces from the input print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
import mpmath # for roots of unity import numpy as np class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None ) -> Tuple: # Input as list A : Optional[Any] =list(poly_a or [0] )[:] A : int =list(poly_b or [0] )[:] # Remove leading zero coefficients while self.polyA[-1] == 0: self.polyA.pop() A : List[str] =len(self.polyA ) while self.polyB[-1] == 0: self.polyB.pop() A : Optional[int] =len(self.polyB ) # Add 0 to make lengths equal a power of 2 A : List[Any] =int( 2 ** np.ceil(np.loga(len(self.polyA ) + len(self.polyB ) - 1 ) ) ) while len(self.polyA ) < self.c_max_length: self.polyA.append(0 ) while len(self.polyB ) < self.c_max_length: self.polyB.append(0 ) # A complex root used for the fourier transform A : Optional[Any] =complex(mpmath.root(x=1 , n=self.c_max_length , k=1 ) ) # The product A : List[Any] =self.__multiply() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: A : str =[[x] for x in self.polyA] if which == 'A' else [[x] for x in self.polyB] # Corner case if len(SCREAMING_SNAKE_CASE__ ) <= 1: return dft[0] # A : List[str] =self.c_max_length // 2 while next_ncol > 0: A : Any =[[] for i in range(SCREAMING_SNAKE_CASE__ )] A : Optional[Any] =self.root**next_ncol # First half of next step A : Tuple =1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(SCREAMING_SNAKE_CASE__ ): new_dft[i].append(dft[i][j] + current_root * dft[i + next_ncol][j] ) current_root *= root # Second half of next step A : Optional[Any] =1 for j in range(self.c_max_length // (next_ncol * 2) ): for i in range(SCREAMING_SNAKE_CASE__ ): new_dft[i].append(dft[i][j] - current_root * dft[i + next_ncol][j] ) current_root *= root # Update A : Dict =new_dft A : Optional[int] =next_ncol // 2 return dft[0] def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : List[Any] =self.__dft('A' ) A : Dict =self.__dft('B' ) A : Optional[Any] =[[dft_a[i] * dft_b[i] for i in range(self.c_max_length )]] del dft_a del dft_b # Corner Case if len(inverce_c[0] ) <= 1: return inverce_c[0] # Inverse DFT A : Union[str, Any] =2 while next_ncol <= self.c_max_length: A : Optional[int] =[[] for i in range(SCREAMING_SNAKE_CASE__ )] A : Any =self.root ** (next_ncol // 2) A : Union[str, Any] =1 # First half of next step for j in range(self.c_max_length // next_ncol ): for i in range(next_ncol // 2 ): # Even positions new_inverse_c[i].append( ( inverce_c[i][j] + inverce_c[i][j + self.c_max_length // next_ncol] ) / 2 ) # Odd positions new_inverse_c[i + next_ncol // 2].append( ( inverce_c[i][j] - inverce_c[i][j + self.c_max_length // next_ncol] ) / (2 * current_root) ) current_root *= root # Update A : Any =new_inverse_c next_ncol *= 2 # Unpack A : List[Any] =[round(x[0].real , 8 ) + round(x[0].imag , 8 ) * 1j for x in inverce_c] # Remove leading 0's while inverce_c[-1] == 0: inverce_c.pop() return inverce_c def __str__( self : str ) -> int: A : List[Any] ='A = ' + ' + '.join( f'{coef}*x^{i}' for coef, i in enumerate(self.polyA[: self.len_A] ) ) A : List[str] ='B = ' + ' + '.join( f'{coef}*x^{i}' for coef, i in enumerate(self.polyB[: self.len_B] ) ) A : List[Any] ='A*B = ' + ' + '.join( f'{coef}*x^{i}' for coef, i in enumerate(self.product ) ) return f'{a}\n{b}\n{c}' # Unit tests if __name__ == "__main__": import doctest doctest.testmod()
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bert import BertTokenizer _lowercase : str =logging.get_logger(__name__) _lowercase : Optional[int] ={'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowercase : List[str] ={ '''vocab_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt''' ), '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''', '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt''' ), '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''', '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''', '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''', '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''', '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''', '''bert-base-multilingual-uncased''': ( '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json''' ), '''bert-base-multilingual-cased''': ( '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json''' ), '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''', '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''', '''bert-large-uncased-whole-word-masking''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json''' ), '''bert-large-uncased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-large-cased-whole-word-masking-finetuned-squad''': ( '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json''' ), '''bert-base-cased-finetuned-mrpc''': ( '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-cased''': ( '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json''' ), '''bert-base-german-dbmdz-uncased''': ( '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-cased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json''' ), '''TurkuNLP/bert-base-finnish-uncased-v1''': ( '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json''' ), '''wietsedv/bert-base-dutch-cased''': ( '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json''' ), }, } _lowercase : str ={ '''bert-base-uncased''': 5_1_2, '''bert-large-uncased''': 5_1_2, '''bert-base-cased''': 5_1_2, '''bert-large-cased''': 5_1_2, '''bert-base-multilingual-uncased''': 5_1_2, '''bert-base-multilingual-cased''': 5_1_2, '''bert-base-chinese''': 5_1_2, '''bert-base-german-cased''': 5_1_2, '''bert-large-uncased-whole-word-masking''': 5_1_2, '''bert-large-cased-whole-word-masking''': 5_1_2, '''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_1_2, '''bert-large-cased-whole-word-masking-finetuned-squad''': 5_1_2, '''bert-base-cased-finetuned-mrpc''': 5_1_2, '''bert-base-german-dbmdz-cased''': 5_1_2, '''bert-base-german-dbmdz-uncased''': 5_1_2, '''TurkuNLP/bert-base-finnish-cased-v1''': 5_1_2, '''TurkuNLP/bert-base-finnish-uncased-v1''': 5_1_2, '''wietsedv/bert-base-dutch-cased''': 5_1_2, } _lowercase : Optional[int] ={ '''bert-base-uncased''': {'''do_lower_case''': True}, '''bert-large-uncased''': {'''do_lower_case''': True}, '''bert-base-cased''': {'''do_lower_case''': False}, '''bert-large-cased''': {'''do_lower_case''': False}, '''bert-base-multilingual-uncased''': {'''do_lower_case''': True}, '''bert-base-multilingual-cased''': {'''do_lower_case''': False}, '''bert-base-chinese''': {'''do_lower_case''': False}, '''bert-base-german-cased''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False}, '''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True}, '''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False}, '''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False}, '''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True}, '''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False}, '''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True}, '''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False}, } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = VOCAB_FILES_NAMES lowercase : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : Union[str, Any] = PRETRAINED_INIT_CONFIGURATION lowercase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[Any] = BertTokenizer def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]="[UNK]" , SCREAMING_SNAKE_CASE__ : List[Any]="[SEP]" , SCREAMING_SNAKE_CASE__ : str="[PAD]" , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="[MASK]" , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=None , **SCREAMING_SNAKE_CASE__ : str , ) -> Optional[Any]: super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) A : List[str] =json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get('strip_accents' , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get('handle_chinese_chars' , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): A : Any =getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop('type' ) ) A : Union[str, Any] =do_lower_case A : List[str] =strip_accents A : Union[str, Any] =tokenize_chinese_chars A : str =normalizer_class(**SCREAMING_SNAKE_CASE__ ) A : Dict =do_lower_case def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str=None ) -> Dict: A : Union[str, Any] =[self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: A : List[Any] =[self.sep_token_id] A : List[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 ) * [0] + len(token_ids_a + sep ) * [1] def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: A : Union[str, Any] =self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsรฉ.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) _lowercase : Union[str, Any] ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int =['''NllbTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[Any] =['''NllbTokenizerFast'''] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys _lowercase : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
from __future__ import annotations from collections.abc import Callable _lowercase : List[Any] =list[list[float | int]] def A__ ( lowercase: Matrix, lowercase: Matrix ) -> Matrix: A : int =len(lowercase ) A : Matrix =[[0 for _ in range(size + 1 )] for _ in range(lowercase )] A : int A : int A : int A : int A : int A : float for row in range(lowercase ): for col in range(lowercase ): A : Union[str, Any] =matrix[row][col] A : Dict =vector[row][0] A : Tuple =0 A : Any =0 while row < size and col < size: # pivoting A : str =max((abs(augmented[rowa][col] ), rowa) for rowa in range(lowercase, lowercase ) )[ 1 ] if augmented[pivot_row][col] == 0: col += 1 continue else: A , A : Union[str, Any] =augmented[pivot_row], augmented[row] for rowa in range(row + 1, lowercase ): A : Union[str, Any] =augmented[rowa][col] / augmented[row][col] A : List[str] =0 for cola in range(col + 1, size + 1 ): augmented[rowa][cola] -= augmented[row][cola] * ratio row += 1 col += 1 # back substitution for col in range(1, lowercase ): for row in range(lowercase ): A : List[Any] =augmented[row][col] / augmented[col][col] for cola in range(lowercase, size + 1 ): augmented[row][cola] -= augmented[col][cola] * ratio # round to get rid of numbers like 2.000000000000004 return [ [round(augmented[row][size] / augmented[row][row], 10 )] for row in range(lowercase ) ] def A__ ( lowercase: list[int] ) -> Callable[[int], int]: A : int =len(lowercase ) A : Matrix =[[0 for _ in range(lowercase )] for _ in range(lowercase )] A : Matrix =[[0] for _ in range(lowercase )] A : Matrix A : int A : int A : int for x_val, y_val in enumerate(lowercase ): for col in range(lowercase ): A : Any =(x_val + 1) ** (size - col - 1) A : List[str] =y_val A : Tuple =solve(lowercase, lowercase ) def interpolated_func(lowercase: int ) -> int: return sum( round(coeffs[x_val][0] ) * (var ** (size - x_val - 1)) for x_val in range(lowercase ) ) return interpolated_func def A__ ( lowercase: int ) -> int: return ( 1 - variable + variable**2 - variable**3 + variable**4 - variable**5 + variable**6 - variable**7 + variable**8 - variable**9 + variable**10 ) def A__ ( lowercase: Callable[[int], int] = question_function, lowercase: int = 10 ) -> int: A : list[int] =[func(lowercase ) for x_val in range(1, order + 1 )] A : list[Callable[[int], int]] =[ interpolate(data_points[:max_coeff] ) for max_coeff in range(1, order + 1 ) ] A : int =0 A : Callable[[int], int] A : int for poly in polynomials: A : Optional[Any] =1 while func(lowercase ) == poly(lowercase ): x_val += 1 ret += poly(lowercase ) return ret if __name__ == "__main__": print(f'''{solution() = }''')
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def A__ ( lowercase: Any, lowercase: int, lowercase: List[str], lowercase: List[Any]="attention" ) -> Dict: A : Any =params[F'{prefix}/layers_{i}/{layer_name}/key/kernel'] A : List[str] =params[F'{prefix}/layers_{i}/{layer_name}/out/kernel'] A : str =params[F'{prefix}/layers_{i}/{layer_name}/query/kernel'] A : Any =params[F'{prefix}/layers_{i}/{layer_name}/value/kernel'] return k, o, q, v def A__ ( lowercase: Dict, lowercase: Dict, lowercase: Any, lowercase: Union[str, Any]=False ) -> Tuple: if split_mlp_wi: A : Tuple =params[F'{prefix}/layers_{i}/mlp/wi_0/kernel'] A : Union[str, Any] =params[F'{prefix}/layers_{i}/mlp/wi_1/kernel'] A : Optional[int] =(wi_a, wi_a) else: A : Optional[int] =params[F'{prefix}/layers_{i}/mlp/wi/kernel'] A : Tuple =params[F'{prefix}/layers_{i}/mlp/wo/kernel'] return wi, wo def A__ ( lowercase: str, lowercase: Optional[Any], lowercase: Dict, lowercase: List[str] ) -> List[Any]: return params[F'{prefix}/layers_{i}/{layer_name}/scale'] def A__ ( lowercase: dict, *, lowercase: int, lowercase: bool ) -> List[Any]: A : Optional[int] =traverse_util.flatten_dict(variables['target'] ) A : List[str] ={'/'.join(lowercase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi A : List[str] ='encoder/layers_0/mlp/wi_0/kernel' in old print('Split MLP:', lowercase ) A : List[str] =collections.OrderedDict() # Shared embeddings. A : Union[str, Any] =old['token_embedder/embedding'] # Encoder. for i in range(lowercase ): # Block i, layer 0 (Self Attention). A : str =tax_layer_norm_lookup(lowercase, lowercase, 'encoder', 'pre_attention_layer_norm' ) A , A , A , A : Optional[Any] =tax_attention_lookup(lowercase, lowercase, 'encoder', 'attention' ) A : Any =layer_norm A : Tuple =k.T A : Tuple =o.T A : int =q.T A : Any =v.T # Block i, layer 1 (MLP). A : Dict =tax_layer_norm_lookup(lowercase, lowercase, 'encoder', 'pre_mlp_layer_norm' ) A , A : Optional[Any] =tax_mlp_lookup(lowercase, lowercase, 'encoder', lowercase ) A : Optional[Any] =layer_norm if split_mlp_wi: A : Tuple =wi[0].T A : List[Any] =wi[1].T else: A : Optional[Any] =wi.T A : int =wo.T A : List[str] =old[ 'encoder/relpos_bias/rel_embedding' ].T A : Optional[int] =old['encoder/encoder_norm/scale'] if not is_encoder_only: # Decoder. for i in range(lowercase ): # Block i, layer 0 (Self Attention). A : int =tax_layer_norm_lookup(lowercase, lowercase, 'decoder', 'pre_self_attention_layer_norm' ) A , A , A , A : Optional[int] =tax_attention_lookup(lowercase, lowercase, 'decoder', 'self_attention' ) A : Optional[int] =layer_norm A : List[str] =k.T A : Tuple =o.T A : List[str] =q.T A : Union[str, Any] =v.T # Block i, layer 1 (Cross Attention). A : str =tax_layer_norm_lookup(lowercase, lowercase, 'decoder', 'pre_cross_attention_layer_norm' ) A , A , A , A : Optional[Any] =tax_attention_lookup(lowercase, lowercase, 'decoder', 'encoder_decoder_attention' ) A : List[str] =layer_norm A : Optional[int] =k.T A : Optional[Any] =o.T A : List[str] =q.T A : Optional[int] =v.T # Block i, layer 2 (MLP). A : Dict =tax_layer_norm_lookup(lowercase, lowercase, 'decoder', 'pre_mlp_layer_norm' ) A , A : Tuple =tax_mlp_lookup(lowercase, lowercase, 'decoder', lowercase ) A : int =layer_norm if split_mlp_wi: A : Any =wi[0].T A : Tuple =wi[1].T else: A : Optional[Any] =wi.T A : Union[str, Any] =wo.T A : Optional[int] =old['decoder/decoder_norm/scale'] A : List[str] =old[ 'decoder/relpos_bias/rel_embedding' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: A : Optional[Any] =old['decoder/logits_dense/kernel'].T return new def A__ ( lowercase: Union[str, Any], lowercase: bool ) -> int: A : List[str] =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: A : List[Any] =state_dict['shared.weight'] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: A : 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.' ) A : List[str] =state_dict['shared.weight'] return state_dict def A__ ( lowercase: Any, lowercase: Optional[int], lowercase: List[Any], lowercase: Tuple ) -> Optional[int]: A : str =checkpoints.load_tax_checkpoint(lowercase ) A : Union[str, Any] =convert_tax_to_pytorch(lowercase, num_layers=config.num_layers, is_encoder_only=lowercase ) A : List[Any] =make_state_dict(lowercase, lowercase ) model.load_state_dict(lowercase, strict=lowercase ) def A__ ( lowercase: Union[str, Any], lowercase: Optional[int], lowercase: List[Any], lowercase: bool = False ) -> List[Any]: A : List[str] =TaConfig.from_json_file(lowercase ) 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: A : Optional[Any] =TaEncoderModel(lowercase ) else: A : Optional[Any] =TaForConditionalGeneration(lowercase ) # Load weights from tf checkpoint load_tax_weights_in_ta(lowercase, lowercase, lowercase, lowercase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowercase ) # Verify that we can load the checkpoint. model.from_pretrained(lowercase ) print('Done' ) if __name__ == "__main__": _lowercase : Any =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 ) _lowercase : Dict =parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'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. A : Optional[int] =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: A : str =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) 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 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =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: A : Optional[Any] =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) 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 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).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!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =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] ) ): A : Tuple ='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 A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\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()
661
1
def A__ ( lowercase: int, lowercase: list ) -> Dict: _enforce_args(lowercase, lowercase ) if n == 0: return 0 A : Optional[int] =float('-inf' ) for i in range(1, n + 1 ): A : Union[str, Any] =max( lowercase, prices[i - 1] + naive_cut_rod_recursive(n - i, lowercase ) ) return max_revue def A__ ( lowercase: int, lowercase: list ) -> Optional[Any]: _enforce_args(lowercase, lowercase ) A : Dict =[float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase, lowercase, lowercase ) def A__ ( lowercase: int, lowercase: list, lowercase: list ) -> Optional[Any]: if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: A : Dict =float('-inf' ) for i in range(1, n + 1 ): A : int =max( lowercase, prices[i - 1] + _top_down_cut_rod_recursive(n - i, lowercase, lowercase ), ) A : str =max_revenue return max_rev[n] def A__ ( lowercase: int, lowercase: list ) -> Optional[int]: _enforce_args(lowercase, lowercase ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. A : Dict =[float('-inf' ) for _ in range(n + 1 )] A : List[Any] =0 for i in range(1, n + 1 ): A : Dict =max_rev[i] for j in range(1, i + 1 ): A : List[str] =max(lowercase, prices[j - 1] + max_rev[i - j] ) A : int =max_revenue_i return max_rev[n] def A__ ( lowercase: int, lowercase: list ) -> int: if n < 0: A : Tuple =F'n must be greater than or equal to 0. Got n = {n}' raise ValueError(lowercase ) if n > len(lowercase ): A : Dict =( 'Each integral piece of rod must have a corresponding price. ' F'Got n = {n} but length of prices = {len(lowercase )}' ) raise ValueError(lowercase ) def A__ ( ) -> List[str]: A : Optional[Any] =[6, 10, 12, 15, 20, 23] A : List[str] =len(lowercase ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. A : Union[str, Any] =36 A : Dict =top_down_cut_rod(lowercase, lowercase ) A : Tuple =bottom_up_cut_rod(lowercase, lowercase ) A : Union[str, Any] =naive_cut_rod_recursive(lowercase, lowercase ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
def A__ ( lowercase: Tuple, lowercase: int ) -> List[Any]: A : int =0 A : str =len(lowercase ) - 1 while left <= right: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A : List[str] =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowercase ): return None A : Union[str, Any] =sorted_collection[point] if current_item == item: return point else: if point < left: A : Union[str, Any] =left A : Optional[Any] =point elif point > right: A : List[Any] =right A : int =point else: if item < current_item: A : Dict =point - 1 else: A : Tuple =point + 1 return None def A__ ( lowercase: Optional[Any], lowercase: Optional[int], lowercase: str, lowercase: Optional[int] ) -> int: # avoid divided by 0 during interpolation if sorted_collection[left] == sorted_collection[right]: if sorted_collection[left] == item: return left else: return None A : Tuple =left + ((item - sorted_collection[left]) * (right - left)) // ( sorted_collection[right] - sorted_collection[left] ) # out of range check if point < 0 or point >= len(lowercase ): return None if sorted_collection[point] == item: return point elif point < left: return interpolation_search_by_recursion(lowercase, lowercase, lowercase, lowercase ) elif point > right: return interpolation_search_by_recursion(lowercase, lowercase, lowercase, lowercase ) else: if sorted_collection[point] > item: return interpolation_search_by_recursion( lowercase, lowercase, lowercase, point - 1 ) else: return interpolation_search_by_recursion( lowercase, lowercase, point + 1, lowercase ) def A__ ( lowercase: Tuple ) -> Any: if collection != sorted(lowercase ): raise ValueError('Collection must be ascending sorted' ) return True if __name__ == "__main__": import sys _lowercase : List[str] =0 if debug == 1: _lowercase : Optional[int] =[1_0, 3_0, 4_0, 4_5, 5_0, 6_6, 7_7, 9_3] try: __assert_sorted(collection) except ValueError: sys.exit('''Sequence must be ascending sorted to apply interpolation search''') _lowercase : List[Any] =6_7 _lowercase : Any =interpolation_search(collection, target) if result is not None: print(f'''{target} found at positions: {result}''') else: print('''Not found''')
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def A__ ( lowercase: Dict, lowercase: Union[str, Any] ) -> Optional[int]: A : List[str] =[] for part_id in partition_order: A : Optional[Any] =df.where(F'SPARK_PARTITION_ID() = {part_id}' ).collect() for row_idx, row in enumerate(lowercase ): expected_row_ids_and_row_dicts.append((F'{part_id}_{row_idx}', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> List[Any]: A : Optional[int] =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : Any =spark.range(100 ).repartition(1 ) A : List[str] =Spark(lowercase ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> str: A : List[Any] =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : str =spark.range(10 ).repartition(2 ) A : Union[str, Any] =[1, 0] A : Optional[Any] =_generate_iterable_examples(lowercase, lowercase ) # Reverse the partitions. A : Dict =_get_expected_row_ids_and_row_dicts_for_partition_order(lowercase, lowercase ) for i, (row_id, row_dict) in enumerate(generate_fn() ): A , A : Any =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> Union[str, Any]: A : Dict =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : int =spark.range(10 ).repartition(1 ) A : str =SparkExamplesIterable(lowercase ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(lowercase ): assert row_id == F'0_{i}' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> int: A : str =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : Union[str, Any] =spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('numpy.random.Generator' ) as generator_mock: A : Dict =lambda lowercase : x.reverse() A : List[str] =_get_expected_row_ids_and_row_dicts_for_partition_order(lowercase, [2, 1, 0] ) A : Tuple =SparkExamplesIterable(lowercase ).shuffle_data_sources(lowercase ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(lowercase ): A , A : str =expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> Optional[int]: A : Optional[int] =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : Dict =spark.range(20 ).repartition(4 ) # Partitions 0 and 2 A : Dict =SparkExamplesIterable(lowercase ).shard_data_sources(worker_id=0, num_workers=2 ) assert shard_it_a.n_shards == 2 A : Union[str, Any] =_get_expected_row_ids_and_row_dicts_for_partition_order(lowercase, [0, 2] ) for i, (row_id, row_dict) in enumerate(lowercase ): A , A : Dict =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 A : Any =SparkExamplesIterable(lowercase ).shard_data_sources(worker_id=1, num_workers=2 ) assert shard_it_a.n_shards == 2 A : Any =_get_expected_row_ids_and_row_dicts_for_partition_order(lowercase, [1, 3] ) for i, (row_id, row_dict) in enumerate(lowercase ): A , A : str =expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def A__ ( ) -> Optional[int]: A : Optional[Any] =pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() A : int =spark.range(100 ).repartition(1 ) A : Optional[Any] =Spark(lowercase ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase : List[str] =logging.get_logger(__name__) _lowercase : Any ={ '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = "yolos" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str]=7_68 , SCREAMING_SNAKE_CASE__ : Tuple=12 , SCREAMING_SNAKE_CASE__ : str=12 , SCREAMING_SNAKE_CASE__ : str=30_72 , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : str=0.0 , SCREAMING_SNAKE_CASE__ : int=0.0 , SCREAMING_SNAKE_CASE__ : Optional[int]=0.0_2 , SCREAMING_SNAKE_CASE__ : Any=1e-12 , SCREAMING_SNAKE_CASE__ : List[str]=[5_12, 8_64] , SCREAMING_SNAKE_CASE__ : List[str]=16 , SCREAMING_SNAKE_CASE__ : str=3 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : int=1_00 , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Dict=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=5 , SCREAMING_SNAKE_CASE__ : Optional[int]=2 , SCREAMING_SNAKE_CASE__ : List[str]=5 , SCREAMING_SNAKE_CASE__ : List[str]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.1 , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : str =hidden_size A : Tuple =num_hidden_layers A : str =num_attention_heads A : Any =intermediate_size A : List[Any] =hidden_act A : str =hidden_dropout_prob A : List[str] =attention_probs_dropout_prob A : Tuple =initializer_range A : str =layer_norm_eps A : Tuple =image_size A : Union[str, Any] =patch_size A : Union[str, Any] =num_channels A : Union[str, Any] =qkv_bias A : int =num_detection_tokens A : List[str] =use_mid_position_embeddings A : str =auxiliary_loss # Hungarian matcher A : Optional[Any] =class_cost A : List[Any] =bbox_cost A : Optional[int] =giou_cost # Loss coefficients A : List[str] =bbox_loss_coefficient A : int =giou_loss_coefficient A : List[Any] =eos_coefficient class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> float: return 1e-4 @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> int: return 12
661
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Any =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
def A__ ( lowercase: int ) -> None: A : str =generate_pascal_triangle(lowercase ) for row_idx in range(lowercase ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=' ' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx], end=' ' ) else: print(triangle[row_idx][col_idx], end='' ) print() def A__ ( lowercase: int ) -> list[list[int]]: if not isinstance(lowercase, lowercase ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) A : list[list[int]] =[] for current_row_idx in range(lowercase ): A : List[str] =populate_current_row(lowercase, lowercase ) triangle.append(lowercase ) return triangle def A__ ( lowercase: list[list[int]], lowercase: int ) -> list[int]: A : Tuple =[-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 A , A : List[str] =1, 1 for current_col_idx in range(1, lowercase ): calculate_current_element( lowercase, lowercase, lowercase, lowercase ) return current_row def A__ ( lowercase: list[list[int]], lowercase: list[int], lowercase: int, lowercase: int, ) -> None: A : Optional[int] =triangle[current_row_idx - 1][current_col_idx - 1] A : Optional[Any] =triangle[current_row_idx - 1][current_col_idx] A : int =above_to_left_elt + above_to_right_elt def A__ ( lowercase: int ) -> list[list[int]]: if not isinstance(lowercase, lowercase ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) A : list[list[int]] =[[1]] for row_index in range(1, lowercase ): A : Dict =[0] + result[-1] + [0] A : Union[str, Any] =row_index + 1 # Calculate the number of distinct elements in a row A : Any =sum(divmod(lowercase, 2 ) ) A : Any =[ temp_row[i - 1] + temp_row[i] for i in range(1, distinct_elements + 1 ) ] A : Dict =row_first_half[: (row_index + 1) // 2] row_second_half.reverse() A : Any =row_first_half + row_second_half result.append(lowercase ) return result def A__ ( ) -> None: from collections.abc import Callable from timeit import timeit def benchmark_a_function(lowercase: Callable, lowercase: int ) -> None: A : int =F'{func.__name__}({value})' A : Optional[int] =timeit(F'__main__.{call}', setup='import __main__' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(F'{call:38} -- {timing:.4f} seconds' ) for value in range(15 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(lowercase, lowercase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''๐Ÿค— Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : List[str] lowercase : Optional[str] = None # Automatically constructed lowercase : ClassVar[str] = "dict" lowercase : ClassVar[Any] = None lowercase : str = field(default="Translation" , init=lowerCAmelCase_ , repr=lowerCAmelCase_ ) def __call__( self : Optional[int] ) -> Any: return pa.struct({lang: pa.string() for lang in sorted(self.languages )} ) def SCREAMING_SNAKE_CASE_ ( self : str ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Value return {k: Value('string' ) for k in sorted(self.languages )} @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : Optional[List] = None lowercase : Optional[int] = None lowercase : Optional[str] = None # Automatically constructed lowercase : ClassVar[str] = "dict" lowercase : ClassVar[Any] = None lowercase : str = field(default="TranslationVariableLanguages" , init=lowerCAmelCase_ , repr=lowerCAmelCase_ ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: A : Tuple =sorted(set(self.languages ) ) if self.languages else None A : Optional[Any] =len(self.languages ) if self.languages else None def __call__( self : Optional[int] ) -> Dict: return pa.struct({'language': pa.list_(pa.string() ), 'translation': pa.list_(pa.string() )} ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[str]: A : Tuple =set(self.languages ) if self.languages and set(SCREAMING_SNAKE_CASE__ ) - lang_set: raise ValueError( f'Some languages in example ({", ".join(sorted(set(SCREAMING_SNAKE_CASE__ ) - lang_set ) )}) are not in valid set ({", ".join(SCREAMING_SNAKE_CASE__ )}).' ) # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. A : List[str] =[] for lang, text in translation_dict.items(): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): translation_tuples.append((lang, text) ) else: translation_tuples.extend([(lang, el) for el in text] ) # Ensure translations are in ascending order by language code. A , A : Any =zip(*sorted(SCREAMING_SNAKE_CASE__ ) ) return {"language": languages, "translation": translations} def SCREAMING_SNAKE_CASE_ ( self : str ) -> Union["FeatureType", Dict[str, "FeatureType"]]: from .features import Sequence, Value return { "language": Sequence(Value('string' ) ), "translation": Sequence(Value('string' ) ), }
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
def A__ ( lowercase: str, lowercase: str ) -> float: def get_matched_characters(lowercase: str, lowercase: str ) -> str: A : Tuple =[] A : Optional[Any] =min(len(_stra ), len(_stra ) ) // 2 for i, l in enumerate(_stra ): A : Any =int(max(0, i - limit ) ) A : int =int(min(i + limit + 1, len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowercase ) A : List[str] =F'{_stra[0:_stra.index(lowercase )]} {_stra[_stra.index(lowercase ) + 1:]}' return "".join(lowercase ) # matching characters A : Union[str, Any] =get_matched_characters(lowercase, lowercase ) A : Any =get_matched_characters(lowercase, lowercase ) A : Union[str, Any] =len(lowercase ) # transposition A : Optional[int] =( len([(ca, ca) for ca, ca in zip(lowercase, lowercase ) if ca != ca] ) // 2 ) if not match_count: A : Dict =0.0 else: A : List[Any] =( 1 / 3 * ( match_count / len(lowercase ) + match_count / len(lowercase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters A : 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'''))
661
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 SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowercase : Union[str, Any] ={ '''configuration_mctct''': ['''MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MCTCTConfig'''], '''feature_extraction_mctct''': ['''MCTCTFeatureExtractor'''], '''processing_mctct''': ['''MCTCTProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Tuple =[ '''MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MCTCTForCTC''', '''MCTCTModel''', '''MCTCTPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig from .feature_extraction_mctct import MCTCTFeatureExtractor from .processing_mctct import MCTCTProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel else: import sys _lowercase : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
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 : Union[str, Any] ={ '''configuration_xlm_roberta''': [ '''XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMRobertaConfig''', '''XLMRobertaOnnxConfig''', ], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict =['''XLMRobertaTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Dict =['''XLMRobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[str] =[ '''XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLMRobertaForCausalLM''', '''XLMRobertaForMaskedLM''', '''XLMRobertaForMultipleChoice''', '''XLMRobertaForQuestionAnswering''', '''XLMRobertaForSequenceClassification''', '''XLMRobertaForTokenClassification''', '''XLMRobertaModel''', '''XLMRobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[Any] =[ '''TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLMRobertaForCausalLM''', '''TFXLMRobertaForMaskedLM''', '''TFXLMRobertaForMultipleChoice''', '''TFXLMRobertaForQuestionAnswering''', '''TFXLMRobertaForSequenceClassification''', '''TFXLMRobertaForTokenClassification''', '''TFXLMRobertaModel''', '''TFXLMRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : List[Any] =[ '''FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''FlaxXLMRobertaForMaskedLM''', '''FlaxXLMRobertaForCausalLM''', '''FlaxXLMRobertaForMultipleChoice''', '''FlaxXLMRobertaForQuestionAnswering''', '''FlaxXLMRobertaForSequenceClassification''', '''FlaxXLMRobertaForTokenClassification''', '''FlaxXLMRobertaModel''', '''FlaxXLMRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaConfig, XLMRobertaOnnxConfig, ) try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta import XLMRobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlm_roberta_fast import XLMRobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta import ( XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaForCausalLM, XLMRobertaForMaskedLM, XLMRobertaForMultipleChoice, XLMRobertaForQuestionAnswering, XLMRobertaForSequenceClassification, XLMRobertaForTokenClassification, XLMRobertaModel, XLMRobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm_roberta import ( TF_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMRobertaForCausalLM, TFXLMRobertaForMaskedLM, TFXLMRobertaForMultipleChoice, TFXLMRobertaForQuestionAnswering, TFXLMRobertaForSequenceClassification, TFXLMRobertaForTokenClassification, TFXLMRobertaModel, TFXLMRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xlm_roberta import ( FLAX_XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxXLMRobertaForCausalLM, FlaxXLMRobertaForMaskedLM, FlaxXLMRobertaForMultipleChoice, FlaxXLMRobertaForQuestionAnswering, FlaxXLMRobertaForSequenceClassification, FlaxXLMRobertaForTokenClassification, FlaxXLMRobertaModel, FlaxXLMRobertaPreTrainedModel, ) else: import sys _lowercase : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''๐Ÿค— Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _lowercase : str =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Any ) -> None: warnings.warn( 'The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DeiTImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
def A__ ( lowercase: float, lowercase: float ) -> float: if mass < 0: raise ValueError('The mass of a body cannot be negative' ) return 0.5 * mass * abs(lowercase ) * abs(lowercase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
import random class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : str ) -> tuple[list[int], list[int]]: A : List[Any] =[ord(SCREAMING_SNAKE_CASE__ ) for i in text] A : int =[] A : Any =[] for i in plain: A : List[str] =random.randint(1 , 3_00 ) A : Optional[Any] =(i + k) * k cipher.append(SCREAMING_SNAKE_CASE__ ) key.append(SCREAMING_SNAKE_CASE__ ) return cipher, key @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : list[int] , SCREAMING_SNAKE_CASE__ : list[int] ) -> str: A : Union[str, Any] =[] for i in range(len(SCREAMING_SNAKE_CASE__ ) ): A : Union[str, Any] =int((cipher[i] - (key[i]) ** 2) / key[i] ) plain.append(chr(SCREAMING_SNAKE_CASE__ ) ) return "".join(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": _lowercase , _lowercase : List[str] =Onepad().encrypt('''Hello''') print(c, k) print(Onepad().decrypt(c, k))
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : int = ["torch", "transformers", "onnx"] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : int , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = ["torch", "transformers", "onnx"] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> int: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : int , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = ["torch", "transformers", "onnx"] def __init__( self : Dict , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Any , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = ["torch", "transformers", "onnx"] def __init__( self : List[Any] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[str] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : List[str] = ["torch", "transformers", "onnx"] def __init__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[int] , *SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : Any ) -> Dict: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Optional[Any] , *SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) class SCREAMING_SNAKE_CASE_ ( metaclass=lowerCAmelCase_ ): '''simple docstring''' lowercase : Union[str, Any] = ["torch", "transformers", "onnx"] def __init__( self : Any , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: requires_backends(self , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Tuple , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[Any]: requires_backends(cls , ['torch', 'transformers', 'onnx'] ) @classmethod def SCREAMING_SNAKE_CASE_ ( cls : Dict , *SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: requires_backends(cls , ['torch', 'transformers', 'onnx'] )
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation _lowercase : Optional[Any] =logging.get_logger(__name__) _lowercase : Dict ={ '''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_config_file''': '''tokenizer_config.json''', } _lowercase : Any ={ '''vocab_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json'''}, '''merges_file''': {'''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt'''}, '''tokenizer_config_file''': { '''facebook/blenderbot-3B''': '''https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json''' }, } _lowercase : Any ={'''facebook/blenderbot-3B''': 1_2_8} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def A__ ( ) -> str: A : Optional[int] =( list(range(ord('!' ), ord('~' ) + 1 ) ) + list(range(ord('ยก' ), ord('ยฌ' ) + 1 ) ) + list(range(ord('ยฎ' ), ord('รฟ' ) + 1 ) ) ) A : Union[str, Any] =bs[:] A : Optional[int] =0 for b in range(2**8 ): if b not in bs: bs.append(lowercase ) cs.append(2**8 + n ) n += 1 A : Any =[chr(lowercase ) for n in cs] return dict(zip(lowercase, lowercase ) ) def A__ ( lowercase: Dict ) -> Any: A : List[str] =set() A : Tuple =word[0] for char in word[1:]: pairs.add((prev_char, char) ) A : List[str] =char return pairs class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = VOCAB_FILES_NAMES lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Union[str, Any] = ["input_ids", "attention_mask"] def __init__( self : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str="replace" , SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : str="</s>" , SCREAMING_SNAKE_CASE__ : str="</s>" , SCREAMING_SNAKE_CASE__ : Any="<s>" , SCREAMING_SNAKE_CASE__ : Tuple="<unk>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<pad>" , SCREAMING_SNAKE_CASE__ : Union[str, Any]="<mask>" , SCREAMING_SNAKE_CASE__ : List[Any]=False , **SCREAMING_SNAKE_CASE__ : Dict , ) -> str: A : List[Any] =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token A : List[Any] =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token A : str =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token A : Tuple =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token A : List[Any] =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token A : List[Any] =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it A : List[Any] =AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token super().__init__( errors=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , add_prefix_space=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) with open(SCREAMING_SNAKE_CASE__ , encoding='utf-8' ) as vocab_handle: A : Dict =json.load(SCREAMING_SNAKE_CASE__ ) A : List[Any] ={v: k for k, v in self.encoder.items()} A : Tuple =errors # how to handle errors in decoding A : Dict =bytes_to_unicode() A : Union[str, Any] ={v: k for k, v in self.byte_encoder.items()} with open(SCREAMING_SNAKE_CASE__ , encoding='utf-8' ) as merges_handle: A : int =merges_handle.read().split('\n' )[1:-1] A : Tuple =[tuple(merge.split() ) for merge in bpe_merges] A : str =dict(zip(SCREAMING_SNAKE_CASE__ , range(len(SCREAMING_SNAKE_CASE__ ) ) ) ) A : Tuple ={} A : Any =add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions A : str =re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: return len(self.encoder ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[int]: return dict(self.encoder , **self.added_tokens_encoder ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: if token in self.cache: return self.cache[token] A : Union[str, Any] =tuple(SCREAMING_SNAKE_CASE__ ) A : Any =get_pairs(SCREAMING_SNAKE_CASE__ ) if not pairs: return token while True: A : Dict =min(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : self.bpe_ranks.get(SCREAMING_SNAKE_CASE__ , float('inf' ) ) ) if bigram not in self.bpe_ranks: break A , A : str =bigram A : Optional[int] =[] A : List[str] =0 while i < len(SCREAMING_SNAKE_CASE__ ): try: A : str =word.index(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) A : int =j if word[i] == first and i < len(SCREAMING_SNAKE_CASE__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 A : List[Any] =tuple(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =new_word if len(SCREAMING_SNAKE_CASE__ ) == 1: break else: A : Optional[int] =get_pairs(SCREAMING_SNAKE_CASE__ ) A : Any =' '.join(SCREAMING_SNAKE_CASE__ ) A : List[str] =word return word def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: A : Union[str, Any] =[] for token in re.findall(self.pat , SCREAMING_SNAKE_CASE__ ): A : Optional[Any] =''.join( self.byte_encoder[b] for b in token.encode('utf-8' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(SCREAMING_SNAKE_CASE__ ).split(' ' ) ) return bpe_tokens def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder.get(self.unk_token ) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: return self.decoder.get(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> str: A : Optional[int] =''.join(SCREAMING_SNAKE_CASE__ ) A : Dict =bytearray([self.byte_decoder[c] for c in text] ).decode('utf-8' , errors=self.errors ) return text def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return A : Union[str, Any] =os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) A : Optional[Any] =os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file'] ) with open(SCREAMING_SNAKE_CASE__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=SCREAMING_SNAKE_CASE__ , ensure_ascii=SCREAMING_SNAKE_CASE__ ) + '\n' ) A : Dict =0 with open(SCREAMING_SNAKE_CASE__ , 'w' , encoding='utf-8' ) as writer: writer.write('#version: 0.2\n' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda SCREAMING_SNAKE_CASE__ : kv[1] ): if index != token_index: logger.warning( f'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.' ' Please check that the tokenizer is not corrupted!' ) A : str =token_index writer.write(' '.join(SCREAMING_SNAKE_CASE__ ) + '\n' ) index += 1 return vocab_file, merge_file def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: A : Any =[self.sep_token_id] A : Optional[Any] =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str]=False , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> str: A : List[str] =kwargs.pop('add_prefix_space' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(SCREAMING_SNAKE_CASE__ ) > 0 and not text[0].isspace()): A : Optional[Any] =' ' + text return (text, kwargs) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> Any: return token_ids_a + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : "Conversation" ) -> List[int]: A : List[Any] =[] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(' ' + text ) else: # Generated responses should contain them already. inputs.append(SCREAMING_SNAKE_CASE__ ) A : str =' '.join(SCREAMING_SNAKE_CASE__ ) A : str =self.encode(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > self.model_max_length: A : Optional[Any] =input_ids[-self.model_max_length :] logger.warning(f'Trimmed input from conversation as it was longer than {self.model_max_length} tokens.' ) return input_ids
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
import warnings from ...utils import logging from .image_processing_beit import BeitImageProcessor _lowercase : Tuple =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : List[str] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( 'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use BeitImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
import random def A__ ( lowercase: int, lowercase: float, lowercase: bool = False ) -> dict: A : dict ={i: [] for i in range(lowercase )} # if probability is greater or equal than 1, then generate a complete graph if probability >= 1: return complete_graph(lowercase ) # if probability is lower or equal than 0, then return a graph without edges if probability <= 0: return graph # for each couple of nodes, add an edge from u to v # if the number randomly generated is greater than probability probability for i in range(lowercase ): for j in range(i + 1, lowercase ): if random.random() < probability: graph[i].append(lowercase ) if not directed: # if the graph is undirected, add an edge in from j to i, either graph[j].append(lowercase ) return graph def A__ ( lowercase: int ) -> dict: return { i: [j for j in range(lowercase ) if i != j] for i in range(lowercase ) } if __name__ == "__main__": import doctest doctest.testmod()
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def A__ ( lowercase: List[str] ) -> Any: if isinstance(lowercase, collections.abc.Iterable ): return x return (x, x) @require_flax class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ) -> int: pass def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: pass def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[Any]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float ) -> List[Any]: A : int =np.abs((a - b) ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'Difference between torch and flax is {diff} (>= {tol}).' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : int ) -> Tuple: A : Optional[int] =VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[int] =FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A : Tuple =model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int]=None , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: A , A : Union[str, Any] =self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : List[str] ={'vision_model': vision_model, 'text_model': text_model} A : str =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE__ ) A : Optional[int] =model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Dict ) -> Tuple: A , A : Any =self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : List[str] ={'vision_model': vision_model, 'text_model': text_model} A : int =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE__ ) A : int =model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) A : List[Any] =output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : int =FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =model(input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) A : List[Any] =after_output[0] A : List[str] =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: A , A : Optional[Any] =self.get_vision_text_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] ={'vision_model': vision_model, 'text_model': text_model} A : List[str] =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =model( input_ids=SCREAMING_SNAKE_CASE__ , pixel_values=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_attentions=SCREAMING_SNAKE_CASE__ ) A : Dict =output.vision_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) A : Tuple =to_atuple(vision_model.config.image_size ) A : int =to_atuple(vision_model.config.patch_size ) A : List[str] =(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) A : Optional[Any] =num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) A : List[Any] =output.text_model_output.attentions self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: pt_model.to(SCREAMING_SNAKE_CASE__ ) pt_model.eval() # prepare inputs A : Any =inputs_dict A : Optional[int] ={k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): A : List[str] =pt_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() A : Union[str, Any] =fx_model(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(SCREAMING_SNAKE_CASE__ , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : int =FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ , from_pt=SCREAMING_SNAKE_CASE__ ) A : int =fx_model_loaded(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(SCREAMING_SNAKE_CASE__ , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =VisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ , from_flax=SCREAMING_SNAKE_CASE__ ) pt_model_loaded.to(SCREAMING_SNAKE_CASE__ ) pt_model_loaded.eval() with torch.no_grad(): A : str =pt_model_loaded(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(SCREAMING_SNAKE_CASE__ , pt_output_loaded.numpy() , 4e-2 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str ) -> int: A : int =VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : int =VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A : Tuple =FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A : Any =convert_pytorch_state_dict_to_flax(pt_model.state_dict() , SCREAMING_SNAKE_CASE__ ) A : Any =fx_state self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: A : Any =VisionTextDualEncoderConfig.from_vision_text_configs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : List[Any] =VisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A : str =FlaxVisionTextDualEncoderModel(SCREAMING_SNAKE_CASE__ ) A : str =load_flax_weights_in_pytorch_model(SCREAMING_SNAKE_CASE__ , fx_model.params ) self.check_pt_flax_equivalence(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: A : List[str] =self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> List[Any]: A : Any =self.prepare_config_and_inputs() self.check_save_load(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[int]: A : Optional[int] =self.prepare_config_and_inputs() self.check_vision_text_output_attention(**SCREAMING_SNAKE_CASE__ ) @is_pt_flax_cross_test def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : Optional[Any] =self.prepare_config_and_inputs() A : Any =config_inputs_dict.pop('vision_config' ) A : Optional[int] =config_inputs_dict.pop('text_config' ) A : Dict =config_inputs_dict self.check_equivalence_pt_to_flax(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_equivalence_flax_to_pt(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A , A : int =self.get_pretrained_model_and_inputs() A : Dict =model_a(**SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =FlaxVisionTextDualEncoderModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =model_a(**SCREAMING_SNAKE_CASE__ ) A : Any =after_outputs[0] A : Any =np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-5 ) @require_flax class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : str =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=SCREAMING_SNAKE_CASE__ , text_from_pt=SCREAMING_SNAKE_CASE__ , ) A : Optional[int] =13 A : str =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) A : Dict =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) A : List[Any] =random_attention_mask([batch_size, 4] ) A : Any ={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[int]: A : Dict =FlaxViTModel(SCREAMING_SNAKE_CASE__ ) A : List[str] =FlaxBertModel(SCREAMING_SNAKE_CASE__ ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Dict: A : Any =FlaxViTModelTester(self ) A : Any =FlaxBertModelTester(self ) A : List[str] =vit_model_tester.prepare_config_and_inputs() A : List[Any] =bert_model_tester.prepare_config_and_inputs() A , A : List[str] =vision_config_and_inputs A , A , A , A : Optional[int] =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : Tuple =FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=SCREAMING_SNAKE_CASE__ , text_from_pt=SCREAMING_SNAKE_CASE__ , ) A : Any =13 A : Tuple =floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) A : Optional[Any] =ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) A : List[Any] =random_attention_mask([batch_size, 4] ) A : List[Any] ={'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: A : Optional[Any] =FlaxCLIPVisionModel(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =FlaxBertModel(SCREAMING_SNAKE_CASE__ ) return vision_model, text_model def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : Any =FlaxCLIPVisionModelTester(self ) A : int =FlaxBertModelTester(self ) A : Optional[int] =clip_model_tester.prepare_config_and_inputs() A : Any =bert_model_tester.prepare_config_and_inputs() A , A : Any =vision_config_and_inputs A , A , A , A : List[Any] =text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Dict =FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) A : List[str] =VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) A : Optional[Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A : int =processor( text=['una foto di un gatto', 'una foto di un cane'] , images=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Tuple =model(**SCREAMING_SNAKE_CASE__ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) A : List[str] =np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]] ) self.assertTrue(np.allclose(outputs.logits_per_image , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) )
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsรฉ.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
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 SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
import warnings from ...utils import logging from .image_processing_perceiver import PerceiverImageProcessor _lowercase : List[str] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple , *SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> None: warnings.warn( 'The class PerceiverFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use PerceiverImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
from collections import defaultdict from math import ceil, sqrt def A__ ( lowercase: int = 1_000_000, lowercase: int = 10 ) -> int: A : defaultdict =defaultdict(lowercase ) for outer_width in range(3, (t_limit // 4) + 2 ): if outer_width * outer_width > t_limit: A : int =max( ceil(sqrt(outer_width * outer_width - t_limit ) ), 1 ) else: A : List[Any] =1 hole_width_lower_bound += (outer_width - hole_width_lower_bound) % 2 for hole_width in range(lowercase, outer_width - 1, 2 ): count[outer_width * outer_width - hole_width * hole_width] += 1 return sum(1 for n in count.values() if 1 <= n <= 10 ) if __name__ == "__main__": print(f'''{solution() = }''')
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'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. A : Optional[int] =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: A : str =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) 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 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =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: A : Optional[Any] =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) 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 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).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!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =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] ) ): A : Tuple ='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 A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\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()
661
1
def A__ ( lowercase: int = 1, lowercase: int = 1_000 ) -> int: A : List[Any] =1 A : Optional[int] =0 for divide_by_number in range(lowercase, digit + 1 ): A : list[int] =[] A : str =numerator for _ in range(1, digit + 1 ): if now_divide in has_been_divided: if longest_list_length < len(lowercase ): A : List[Any] =len(lowercase ) A : int =divide_by_number else: has_been_divided.append(lowercase ) A : Any =now_divide * 10 % divide_by_number return the_digit # Tests if __name__ == "__main__": import doctest doctest.testmod()
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
import sys def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : Optional[int] =len(lowercase ) A : Union[str, Any] =[[0 for x in range(lowercase )] for x in range(lowercase )] A : List[str] =[[0 for x in range(lowercase )] for x in range(lowercase )] for chain_length in range(2, lowercase ): for a in range(1, n - chain_length + 1 ): A : int =a + chain_length - 1 A : Dict =sys.maxsize for c in range(lowercase, lowercase ): A : Optional[int] =( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: A : Optional[int] =cost A : str =c return matrix, sol def A__ ( lowercase: str, lowercase: Optional[int], lowercase: Optional[int] ) -> Any: if i == j: print('A' + str(lowercase ), end=' ' ) else: print('(', end=' ' ) print_optiomal_solution(lowercase, lowercase, optimal_solution[i][j] ) print_optiomal_solution(lowercase, optimal_solution[i][j] + 1, lowercase ) print(')', end=' ' ) def A__ ( ) -> List[str]: A : List[Any] =[30, 35, 15, 5, 10, 20, 25] A : str =len(lowercase ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 A , A : Optional[Any] =matrix_chain_order(lowercase ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(lowercase, 1, n - 1 ) if __name__ == "__main__": main()
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class SCREAMING_SNAKE_CASE_ : '''simple docstring''' lowercase : Optional[Union[str, Path]] = None lowercase : bool = False lowercase : bool = False lowercase : bool = False lowercase : Optional[Dict] = None lowercase : Optional[str] = None lowercase : bool = False lowercase : bool = False lowercase : bool = False lowercase : bool = True lowercase : Optional[int] = None lowercase : int = 1 lowercase : Optional[Union[str, bool]] = None lowercase : bool = False lowercase : Optional[Dict] = None lowercase : Optional[str] = None def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> "DownloadConfig": return self.__class__(**{k: copy.deepcopy(SCREAMING_SNAKE_CASE__ ) for k, v in self.__dict__.items()} )
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def A__ ( lowercase: Tuple ) -> str: # vision encoder if "img_encoder.pos_embed" in name: A : Any =name.replace('img_encoder.pos_embed', 'vision_model.embeddings.position_embeddings' ) if "img_encoder.patch_embed.proj" in name: A : Optional[Any] =name.replace('img_encoder.patch_embed.proj', 'vision_model.embeddings.patch_embeddings.projection' ) if "img_encoder.patch_embed.norm" in name: A : List[str] =name.replace('img_encoder.patch_embed.norm', 'vision_model.embeddings.layernorm' ) if "img_encoder.layers" in name: A : str =name.replace('img_encoder.layers', 'vision_model.encoder.stages' ) if "blocks" in name and "res" not in name: A : int =name.replace('blocks', 'layers' ) if "attn" in name and "pre_assign" not in name: A : Tuple =name.replace('attn', 'self_attn' ) if "proj" in name and "self_attn" in name and "text" not in name: A : Optional[Any] =name.replace('proj', 'out_proj' ) if "pre_assign_attn.attn.proj" in name: A : Optional[int] =name.replace('pre_assign_attn.attn.proj', 'pre_assign_attn.attn.out_proj' ) if "norm1" in name: A : List[str] =name.replace('norm1', 'layer_norm1' ) if "norm2" in name and "pre_assign" not in name: A : Union[str, Any] =name.replace('norm2', 'layer_norm2' ) if "img_encoder.norm" in name: A : Tuple =name.replace('img_encoder.norm', 'vision_model.layernorm' ) # text encoder if "text_encoder.token_embedding" in name: A : Dict =name.replace('text_encoder.token_embedding', 'text_model.embeddings.token_embedding' ) if "text_encoder.positional_embedding" in name: A : Tuple =name.replace('text_encoder.positional_embedding', 'text_model.embeddings.position_embedding.weight' ) if "text_encoder.transformer.resblocks." in name: A : str =name.replace('text_encoder.transformer.resblocks.', 'text_model.encoder.layers.' ) if "ln_1" in name: A : List[Any] =name.replace('ln_1', 'layer_norm1' ) if "ln_2" in name: A : Any =name.replace('ln_2', 'layer_norm2' ) if "c_fc" in name: A : int =name.replace('c_fc', 'fc1' ) if "c_proj" in name: A : str =name.replace('c_proj', 'fc2' ) if "text_encoder" in name: A : Union[str, Any] =name.replace('text_encoder', 'text_model' ) if "ln_final" in name: A : int =name.replace('ln_final', 'final_layer_norm' ) # projection layers if "img_projector.linear_hidden." in name: A : int =name.replace('img_projector.linear_hidden.', 'visual_projection.' ) if "img_projector.linear_out." in name: A : List[str] =name.replace('img_projector.linear_out.', 'visual_projection.3.' ) if "text_projector.linear_hidden" in name: A : Tuple =name.replace('text_projector.linear_hidden', 'text_projection' ) if "text_projector.linear_out" in name: A : Any =name.replace('text_projector.linear_out', 'text_projection.3' ) return name def A__ ( lowercase: Optional[Any], lowercase: Dict ) -> Optional[int]: for key in orig_state_dict.copy().keys(): A : List[Any] =orig_state_dict.pop(lowercase ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A : str =key.split('.' ) A , A : List[Any] =int(key_split[2] ), int(key_split[4] ) A : int =config.vision_config.hidden_size if "weight" in key: A : Optional[Any] =val[:dim, :] A : Dict =val[dim : dim * 2, :] A : int =val[-dim:, :] else: A : str =val[:dim] A : Optional[Any] =val[dim : dim * 2] A : int =val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors A : int =key.split('.' ) A : Dict =int(key_split[3] ) A : List[str] =config.text_config.hidden_size if "weight" in key: A : str =val[:dim, :] A : List[Any] =val[ dim : dim * 2, : ] A : Optional[int] =val[-dim:, :] else: A : Any =val[:dim] A : Optional[int] =val[dim : dim * 2] A : Tuple =val[-dim:] else: A : Any =rename_key(lowercase ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): A : int =val.squeeze_() else: A : Union[str, Any] =val return orig_state_dict def A__ ( ) -> int: A : Union[str, Any] ='http://images.cocodataset.org/val2017/000000039769.jpg' A : int =Image.open(requests.get(lowercase, stream=lowercase ).raw ) return im @torch.no_grad() def A__ ( lowercase: Tuple, lowercase: Dict, lowercase: Union[str, Any]="groupvit-gcc-yfcc", lowercase: Optional[Any]=False ) -> Tuple: A : Any =GroupViTConfig() A : Optional[Any] =GroupViTModel(lowercase ).eval() A : str =torch.load(lowercase, map_location='cpu' )['model'] A : List[Any] =convert_state_dict(lowercase, lowercase ) A , A : Optional[Any] =model.load_state_dict(lowercase, strict=lowercase ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(lowercase ) == 0) # verify result A : List[str] =CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32' ) A : Union[str, Any] =prepare_img() A : Tuple =processor(text=['a photo of a cat', 'a photo of a dog'], images=lowercase, padding=lowercase, return_tensors='pt' ) with torch.no_grad(): A : Optional[int] =model(**lowercase ) if model_name == "groupvit-gcc-yfcc": A : Optional[Any] =torch.tensor([[13.35_23, 6.36_29]] ) elif model_name == "groupvit-gcc-redcaps": A : Union[str, Any] =torch.tensor([[16.18_73, 8.62_30]] ) else: raise ValueError(F'Model name {model_name} not supported.' ) assert torch.allclose(outputs.logits_per_image, lowercase, atol=1e-3 ) processor.save_pretrained(lowercase ) model.save_pretrained(lowercase ) print('Successfully saved processor and model to', lowercase ) if push_to_hub: print('Pushing to the hub...' ) processor.push_to_hub(lowercase, organization='nielsr' ) model.push_to_hub(lowercase, organization='nielsr' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to dump the processor and PyTorch model.''' ) parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to GroupViT checkpoint''') parser.add_argument( '''--model_name''', default='''groupvit-gccy-fcc''', type=str, help='''Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'''', ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model and processor to the ๐Ÿค— hub using the provided `model_name`.''', ) _lowercase : Optional[Any] =parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
661
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Any =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
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, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, logging if is_torch_available(): import torch _lowercase : Tuple =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = ["pixel_values"] def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, int]] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Union[int, float] = 1 / 2_55 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> None: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Any =size if size is not None else {'shortest_edge': 2_56} A : Dict =get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) A : Dict =crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24} A : Optional[Any] =get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='crop_size' ) A : Dict =do_resize A : Union[str, Any] =size A : Optional[Any] =resample A : int =do_center_crop A : Dict =crop_size A : Dict =do_rescale A : Dict =rescale_factor A : str =do_normalize A : Dict =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN A : Tuple =image_std if image_std is not None else IMAGENET_STANDARD_STD def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : PILImageResampling = PILImageResampling.BICUBIC , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> np.ndarray: A : Tuple =get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) if "shortest_edge" not in size: raise ValueError(f'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) A : Tuple =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 SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray: A : int =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` 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 SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> np.ndarray: return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Union[float, List[float]] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Any , ) -> np.ndarray: return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : ImageInput , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : PILImageResampling = None , SCREAMING_SNAKE_CASE__ : bool = None , SCREAMING_SNAKE_CASE__ : Dict[str, int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[float] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[float, List[float]]] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> Any: A : Optional[int] =do_resize if do_resize is not None else self.do_resize A : Tuple =size if size is not None else self.size A : Any =get_size_dict(SCREAMING_SNAKE_CASE__ , default_to_square=SCREAMING_SNAKE_CASE__ ) A : str =resample if resample is not None else self.resample A : Optional[int] =do_center_crop if do_center_crop is not None else self.do_center_crop A : List[str] =crop_size if crop_size is not None else self.crop_size A : List[str] =get_size_dict(SCREAMING_SNAKE_CASE__ , param_name='crop_size' ) A : Any =do_rescale if do_rescale is not None else self.do_rescale A : Tuple =rescale_factor if rescale_factor is not None else self.rescale_factor A : List[Any] =do_normalize if do_normalize is not None else self.do_normalize A : str =image_mean if image_mean is not None else self.image_mean A : Optional[Any] =image_std if image_std is not None else self.image_std A : int =make_list_of_images(SCREAMING_SNAKE_CASE__ ) if not valid_images(SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. A : Tuple =[to_numpy_array(SCREAMING_SNAKE_CASE__ ) for image in images] if do_resize: A : List[str] =[self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images] if do_center_crop: A : Any =[self.center_crop(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ ) for image in images] if do_rescale: A : Union[str, Any] =[self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images] if do_normalize: A : Union[str, Any] =[self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images] A : Union[str, Any] =[to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images] A : List[Any] ={'pixel_values': images} return BatchFeature(data=SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Tuple] = None ) -> Tuple: A : Any =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__ ): A : Union[str, Any] =target_sizes.numpy() A : Optional[Any] =[] for idx in range(len(SCREAMING_SNAKE_CASE__ ) ): A : Union[str, Any] =torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=SCREAMING_SNAKE_CASE__ ) A : Dict =resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(SCREAMING_SNAKE_CASE__ ) else: A : Tuple =logits.argmax(dim=1 ) A : Optional[int] =[semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
from PIL import Image def A__ ( lowercase: Image ) -> Image: A , A : Dict =image.size A : Union[str, Any] =0 A : str =image.load() for i in range(lowercase ): for j in range(lowercase ): A : List[str] =pixels[j, i] mean += pixel mean //= width * height for j in range(lowercase ): for i in range(lowercase ): A : List[Any] =255 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": _lowercase : Union[str, Any] =mean_threshold(Image.open('''path_to_image''').convert('''L''')) image.save('''output_image_path''')
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
from random import shuffle import tensorflow as tf from numpy import array def A__ ( lowercase: List[Any], lowercase: Optional[int] ) -> Any: A : Union[str, Any] =int(lowercase ) assert noofclusters < len(lowercase ) # Find out the dimensionality A : str =len(vectors[0] ) # Will help select random centroids from among the available vectors A : List[str] =list(range(len(lowercase ) ) ) shuffle(lowercase ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. A : Tuple =tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION A : Optional[Any] =tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points A : Optional[int] =[ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowercase ) ] ##These nodes will assign the centroid Variables the appropriate ##values A : str =tf.placeholder('float64', [dim] ) A : str =[] for centroid in centroids: cent_assigns.append(tf.assign(lowercase, lowercase ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) A : int =[tf.Variable(0 ) for i in range(len(lowercase ) )] ##These nodes will assign an assignment Variable the appropriate ##value A : Any =tf.placeholder('int32' ) A : Tuple =[] for assignment in assignments: cluster_assigns.append(tf.assign(lowercase, lowercase ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input A : Optional[int] =tf.placeholder('float', [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors A : Dict =tf.reduce_mean(lowercase, 0 ) ##Node for computing Euclidean distances # Placeholders for input A : Optional[int] =tf.placeholder('float', [dim] ) A : Any =tf.placeholder('float', [dim] ) A : Dict =tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowercase, lowercase ), 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input A : Tuple =tf.placeholder('float', [noofclusters] ) A : Optional[Any] =tf.argmin(lowercase, 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. A : Tuple =tf.initialize_all_variables() # Initialize all variables sess.run(lowercase ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. A : str =100 for _ in range(lowercase ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowercase ) ): A : List[str] =vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. A : str =[ sess.run(lowercase, feed_dict={va: vect, va: sess.run(lowercase )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input A : str =sess.run( lowercase, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowercase ): # Collect all the vectors assigned to this cluster A : Dict =[ vectors[i] for i in range(len(lowercase ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location A : int =sess.run( lowercase, feed_dict={mean_input: array(lowercase )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments A : Optional[int] =sess.run(lowercase ) A : Optional[int] =sess.run(lowercase ) return centroids, assignments
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices _lowercase : List[str] =logging.get_logger(__name__) _lowercase : str ={ '''microsoft/resnet-50''': '''https://huggingface.co/microsoft/resnet-50/blob/main/config.json''', } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "resnet" lowercase : Optional[int] = ["basic", "bottleneck"] def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=64 , SCREAMING_SNAKE_CASE__ : Dict=[2_56, 5_12, 10_24, 20_48] , SCREAMING_SNAKE_CASE__ : int=[3, 4, 6, 3] , SCREAMING_SNAKE_CASE__ : str="bottleneck" , SCREAMING_SNAKE_CASE__ : str="relu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : List[Any] , ) -> List[str]: super().__init__(**SCREAMING_SNAKE_CASE__ ) if layer_type not in self.layer_types: raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types )}' ) A : Optional[Any] =num_channels A : int =embedding_size A : Optional[int] =hidden_sizes A : Any =depths A : Tuple =layer_type A : Union[str, Any] =hidden_act A : str =downsample_in_first_stage A : str =['stem'] + [f'stage{idx}' for idx in range(1 , len(SCREAMING_SNAKE_CASE__ ) + 1 )] A , A : Optional[int] =get_aligned_output_features_output_indices( out_features=SCREAMING_SNAKE_CASE__ , out_indices=SCREAMING_SNAKE_CASE__ , stage_names=self.stage_names ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Dict = version.parse("1.11" ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def SCREAMING_SNAKE_CASE_ ( self : Any ) -> float: return 1e-3
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging _lowercase : List[str] =logging.get_logger(__name__) def A__ ( lowercase: Optional[Any], lowercase: int ) -> str: try: with open(lowercase, 'rb' ) as flax_state_f: A : int =from_bytes(lowercase, flax_state_f.read() ) except UnpicklingError as e: try: with open(lowercase ) as f: if f.read().startswith('version' ): raise OSError( 'You seem to have cloned a repository without having git-lfs installed. Please' ' install git-lfs and run `git lfs install` followed by `git lfs pull` in the' ' folder you cloned.' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(lowercase, lowercase ) def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> Optional[Any]: try: import torch # noqa: F401 except ImportError: logger.error( 'Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see' ' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation' ' instructions.' ) raise # check if we have bf16 weights A : Optional[Any] =flatten_dict(jax.tree_util.tree_map(lambda lowercase : x.dtype == jnp.bfloataa, lowercase ) ).values() if any(lowercase ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( 'Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ' 'before loading those in PyTorch model.' ) A : Any =jax.tree_util.tree_map( lambda lowercase : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params, lowercase ) A : int ='' A : Optional[int] =flatten_dict(lowercase, sep='.' ) A : Tuple =pt_model.state_dict() # keep track of unexpected & missing keys A : Tuple =[] A : List[str] =set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): A : Union[str, Any] =flax_key_tuple.split('.' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: A : Any =flax_key_tuple_array[:-1] + ['weight'] A : List[str] =jnp.transpose(lowercase, (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": A : List[Any] =flax_key_tuple_array[:-1] + ['weight'] A : Optional[int] =flax_tensor.T elif flax_key_tuple_array[-1] == "scale": A : Optional[int] =flax_key_tuple_array[:-1] + ['weight'] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(lowercase ): A : Any =( flax_key_tuple_string.replace('_0', '.0' ) .replace('_1', '.1' ) .replace('_2', '.2' ) .replace('_3', '.3' ) .replace('_4', '.4' ) .replace('_5', '.5' ) .replace('_6', '.6' ) .replace('_7', '.7' ) .replace('_8', '.8' ) .replace('_9', '.9' ) ) A : Optional[Any] ='.'.join(lowercase ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' F'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict A : List[str] =np.asarray(lowercase ) if not isinstance(lowercase, np.ndarray ) else flax_tensor A : str =torch.from_numpy(lowercase ) # remove from missing keys missing_keys.remove(lowercase ) else: # weight is not expected by PyTorch model unexpected_keys.append(lowercase ) pt_model.load_state_dict(lowercase ) # re-transform missing_keys to list A : Union[str, Any] =list(lowercase ) if len(lowercase ) > 0: logger.warning( 'Some weights of the Flax model were not used when initializing the PyTorch model' F' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' F' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This' F' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a' ' FlaxBertForSequenceClassification model).' ) if len(lowercase ) > 0: logger.warning( F'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' F' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ' use it for predictions and inference.' ) return pt_model
661
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 SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
def A__ ( lowercase: int = 10 ) -> str: if not isinstance(lowercase, lowercase ) or n < 0: raise ValueError('Invalid input' ) A : str =10**n A : List[str] =28_433 * (pow(2, 7_830_457, lowercase )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(f'''{solution(1_0) = }''')
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available _lowercase : str ={ '''configuration_biogpt''': ['''BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BioGptConfig'''], '''tokenization_biogpt''': ['''BioGptTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Optional[Any] =[ '''BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BioGptForCausalLM''', '''BioGptForTokenClassification''', '''BioGptForSequenceClassification''', '''BioGptModel''', '''BioGptPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_biogpt import BIOGPT_PRETRAINED_CONFIG_ARCHIVE_MAP, BioGptConfig from .tokenization_biogpt import BioGptTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_biogpt import ( BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptPreTrainedModel, ) else: import sys _lowercase : Tuple =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''๐Ÿค— Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# _lowercase : List[Any] =[ # (stable-diffusion, HF Diffusers) ('''time_embed.0.weight''', '''time_embedding.linear_1.weight'''), ('''time_embed.0.bias''', '''time_embedding.linear_1.bias'''), ('''time_embed.2.weight''', '''time_embedding.linear_2.weight'''), ('''time_embed.2.bias''', '''time_embedding.linear_2.bias'''), ('''input_blocks.0.0.weight''', '''conv_in.weight'''), ('''input_blocks.0.0.bias''', '''conv_in.bias'''), ('''out.0.weight''', '''conv_norm_out.weight'''), ('''out.0.bias''', '''conv_norm_out.bias'''), ('''out.2.weight''', '''conv_out.weight'''), ('''out.2.bias''', '''conv_out.bias'''), ] _lowercase : str =[ # (stable-diffusion, HF Diffusers) ('''in_layers.0''', '''norm1'''), ('''in_layers.2''', '''conv1'''), ('''out_layers.0''', '''norm2'''), ('''out_layers.3''', '''conv2'''), ('''emb_layers.1''', '''time_emb_proj'''), ('''skip_connection''', '''conv_shortcut'''), ] _lowercase : Optional[int] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks _lowercase : Optional[Any] =f'''down_blocks.{i}.resnets.{j}.''' _lowercase : Optional[Any] =f'''input_blocks.{3*i + j + 1}.0.''' unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 _lowercase : Tuple =f'''down_blocks.{i}.attentions.{j}.''' _lowercase : Optional[Any] =f'''input_blocks.{3*i + j + 1}.1.''' unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks _lowercase : Optional[int] =f'''up_blocks.{i}.resnets.{j}.''' _lowercase : int =f'''output_blocks.{3*i + j}.0.''' unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 _lowercase : Optional[Any] =f'''up_blocks.{i}.attentions.{j}.''' _lowercase : Any =f'''output_blocks.{3*i + j}.1.''' unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 _lowercase : List[Any] =f'''down_blocks.{i}.downsamplers.0.conv.''' _lowercase : Any =f'''input_blocks.{3*(i+1)}.0.op.''' unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 _lowercase : Any =f'''up_blocks.{i}.upsamplers.0.''' _lowercase : Any =f'''output_blocks.{3*i + 2}.{1 if i == 0 else 2}.''' unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) _lowercase : List[str] ='''mid_block.attentions.0.''' _lowercase : Optional[Any] ='''middle_block.1.''' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): _lowercase : Optional[int] =f'''mid_block.resnets.{j}.''' _lowercase : Union[str, Any] =f'''middle_block.{2*j}.''' unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def A__ ( lowercase: str ) -> str: # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. A : Optional[int] ={k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: A : Optional[Any] =sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: A : str =v.replace(lowercase, lowercase ) A : Union[str, Any] =v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: A : int =v.replace(lowercase, lowercase ) A : Tuple =v A : List[Any] ={v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# _lowercase : str =[ # (stable-diffusion, HF Diffusers) ('''nin_shortcut''', '''conv_shortcut'''), ('''norm_out''', '''conv_norm_out'''), ('''mid.attn_1.''', '''mid_block.attentions.0.'''), ] for i in range(4): # down_blocks have two resnets for j in range(2): _lowercase : int =f'''encoder.down_blocks.{i}.resnets.{j}.''' _lowercase : Any =f'''encoder.down.{i}.block.{j}.''' vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: _lowercase : Dict =f'''down_blocks.{i}.downsamplers.0.''' _lowercase : str =f'''down.{i}.downsample.''' vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) _lowercase : int =f'''up_blocks.{i}.upsamplers.0.''' _lowercase : int =f'''up.{3-i}.upsample.''' vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): _lowercase : Optional[Any] =f'''decoder.up_blocks.{i}.resnets.{j}.''' _lowercase : int =f'''decoder.up.{3-i}.block.{j}.''' vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): _lowercase : List[str] =f'''mid_block.resnets.{i}.''' _lowercase : Any =f'''mid.block_{i+1}.''' vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) _lowercase : Tuple =[ # (stable-diffusion, HF Diffusers) ('''norm.''', '''group_norm.'''), ('''q.''', '''query.'''), ('''k.''', '''key.'''), ('''v.''', '''value.'''), ('''proj_out.''', '''proj_attn.'''), ] def A__ ( lowercase: Optional[int] ) -> Tuple: # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape, 1, 1 ) def A__ ( lowercase: List[Any] ) -> List[str]: A : Optional[int] ={k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: A : int =v.replace(lowercase, lowercase ) A : List[Any] =v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: A : Union[str, Any] =v.replace(lowercase, lowercase ) A : Dict =v A : Union[str, Any] ={v: vae_state_dict[k] for k, v in mapping.items()} A : Dict =['q', 'k', 'v', 'proj_out'] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if F'mid.attn_1.{weight_name}.weight' in k: print(F'Reshaping {k} for SD format' ) A : Optional[Any] =reshape_weight_for_sd(lowercase ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# _lowercase : Dict =[ # (stable-diffusion, HF Diffusers) ('''resblocks.''', '''text_model.encoder.layers.'''), ('''ln_1''', '''layer_norm1'''), ('''ln_2''', '''layer_norm2'''), ('''.c_fc.''', '''.fc1.'''), ('''.c_proj.''', '''.fc2.'''), ('''.attn''', '''.self_attn'''), ('''ln_final.''', '''transformer.text_model.final_layer_norm.'''), ('''token_embedding.weight''', '''transformer.text_model.embeddings.token_embedding.weight'''), ('''positional_embedding''', '''transformer.text_model.embeddings.position_embedding.weight'''), ] _lowercase : str ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} _lowercase : int =re.compile('''|'''.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp _lowercase : Optional[int] ={'''q''': 0, '''k''': 1, '''v''': 2} def A__ ( lowercase: Tuple ) -> Any: A : Any ={} A : Dict ={} A : Optional[int] ={} for k, v in text_enc_dict.items(): if ( k.endswith('.self_attn.q_proj.weight' ) or k.endswith('.self_attn.k_proj.weight' ) or k.endswith('.self_attn.v_proj.weight' ) ): A : Tuple =k[: -len('.q_proj.weight' )] A : Optional[int] =k[-len('q_proj.weight' )] if k_pre not in capture_qkv_weight: A : Optional[Any] =[None, None, None] A : Tuple =v continue if ( k.endswith('.self_attn.q_proj.bias' ) or k.endswith('.self_attn.k_proj.bias' ) or k.endswith('.self_attn.v_proj.bias' ) ): A : int =k[: -len('.q_proj.bias' )] A : List[Any] =k[-len('q_proj.bias' )] if k_pre not in capture_qkv_bias: A : Optional[int] =[None, None, None] A : Optional[Any] =v continue A : List[Any] =textenc_pattern.sub(lambda lowercase : protected[re.escape(m.group(0 ) )], lowercase ) A : Optional[int] =v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) A : Optional[int] =textenc_pattern.sub(lambda lowercase : protected[re.escape(m.group(0 ) )], lowercase ) A : List[Any] =torch.cat(lowercase ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) A : int =textenc_pattern.sub(lambda lowercase : protected[re.escape(m.group(0 ) )], lowercase ) A : Tuple =torch.cat(lowercase ) return new_state_dict def A__ ( lowercase: int ) -> Union[str, Any]: return text_enc_dict if __name__ == "__main__": _lowercase : Tuple =argparse.ArgumentParser() parser.add_argument('''--model_path''', default=None, type=str, required=True, help='''Path to the model to convert.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the output model.''') parser.add_argument('''--half''', action='''store_true''', help='''Save weights in half precision.''') parser.add_argument( '''--use_safetensors''', action='''store_true''', help='''Save weights use safetensors, default is ckpt.''' ) _lowercase : str =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors _lowercase : Optional[Any] =osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.safetensors''') _lowercase : List[Any] =osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.safetensors''') _lowercase : Union[str, Any] =osp.join(args.model_path, '''text_encoder''', '''model.safetensors''') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): _lowercase : Optional[Any] =load_file(unet_path, device='''cpu''') else: _lowercase : Any =osp.join(args.model_path, '''unet''', '''diffusion_pytorch_model.bin''') _lowercase : Optional[int] =torch.load(unet_path, map_location='''cpu''') if osp.exists(vae_path): _lowercase : List[Any] =load_file(vae_path, device='''cpu''') else: _lowercase : Optional[Any] =osp.join(args.model_path, '''vae''', '''diffusion_pytorch_model.bin''') _lowercase : int =torch.load(vae_path, map_location='''cpu''') if osp.exists(text_enc_path): _lowercase : Union[str, Any] =load_file(text_enc_path, device='''cpu''') else: _lowercase : Optional[int] =osp.join(args.model_path, '''text_encoder''', '''pytorch_model.bin''') _lowercase : Optional[int] =torch.load(text_enc_path, map_location='''cpu''') # Convert the UNet model _lowercase : Dict =convert_unet_state_dict(unet_state_dict) _lowercase : Optional[int] ={'''model.diffusion_model.''' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model _lowercase : str =convert_vae_state_dict(vae_state_dict) _lowercase : Optional[Any] ={'''first_stage_model.''' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper _lowercase : Optional[Any] ='''text_model.encoder.layers.22.layer_norm2.bias''' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm _lowercase : Dict ={'''transformer.''' + k: v for k, v in text_enc_dict.items()} _lowercase : Optional[Any] =convert_text_enc_state_dict_vaa(text_enc_dict) _lowercase : List[Any] ={'''cond_stage_model.model.''' + k: v for k, v in text_enc_dict.items()} else: _lowercase : Dict =convert_text_enc_state_dict(text_enc_dict) _lowercase : int ={'''cond_stage_model.transformer.''' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint _lowercase : Optional[int] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: _lowercase : str ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: _lowercase : Optional[int] ={'''state_dict''': state_dict} torch.save(state_dict, args.checkpoint_path)
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
import argparse import requests import torch from PIL import Image from torchvision.transforms import Compose, Normalize, Resize, ToTensor from transformers import SwinaSRConfig, SwinaSRForImageSuperResolution, SwinaSRImageProcessor def A__ ( lowercase: Optional[Any] ) -> List[str]: A : Dict =SwinaSRConfig() if "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: A : List[Any] =4 elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: A : Dict =4 A : Any =48 A : Optional[int] ='pixelshuffle_aux' elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: A : List[str] =[6, 6, 6, 6] A : Tuple =60 A : Tuple =[6, 6, 6, 6] A : Optional[Any] ='pixelshuffledirect' elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: A : List[str] =4 A : List[str] ='nearest+conv' elif "Swin2SR_Jpeg_dynamic" in checkpoint_url: A : Optional[Any] =1 A : Optional[Any] =1 A : Any =126 A : Any =7 A : Union[str, Any] =2_55.0 A : Dict ='' return config def A__ ( lowercase: List[Any], lowercase: Any ) -> str: if "patch_embed.proj" in name and "layers" not in name: A : str =name.replace('patch_embed.proj', 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: A : str =name.replace('patch_embed.norm', 'embeddings.patch_embeddings.layernorm' ) if "layers" in name: A : Optional[Any] =name.replace('layers', 'encoder.stages' ) if "residual_group.blocks" in name: A : List[Any] =name.replace('residual_group.blocks', 'layers' ) if "attn.proj" in name: A : str =name.replace('attn.proj', 'attention.output.dense' ) if "attn" in name: A : Union[str, Any] =name.replace('attn', 'attention.self' ) if "norm1" in name: A : Optional[int] =name.replace('norm1', 'layernorm_before' ) if "norm2" in name: A : int =name.replace('norm2', 'layernorm_after' ) if "mlp.fc1" in name: A : List[Any] =name.replace('mlp.fc1', 'intermediate.dense' ) if "mlp.fc2" in name: A : List[Any] =name.replace('mlp.fc2', 'output.dense' ) if "q_bias" in name: A : Dict =name.replace('q_bias', 'query.bias' ) if "k_bias" in name: A : Any =name.replace('k_bias', 'key.bias' ) if "v_bias" in name: A : int =name.replace('v_bias', 'value.bias' ) if "cpb_mlp" in name: A : Optional[Any] =name.replace('cpb_mlp', 'continuous_position_bias_mlp' ) if "patch_embed.proj" in name: A : List[str] =name.replace('patch_embed.proj', 'patch_embed.projection' ) if name == "norm.weight": A : Union[str, Any] ='layernorm.weight' if name == "norm.bias": A : Union[str, Any] ='layernorm.bias' if "conv_first" in name: A : Optional[Any] =name.replace('conv_first', 'first_convolution' ) if ( "upsample" in name or "conv_before_upsample" in name or "conv_bicubic" in name or "conv_up" in name or "conv_hr" in name or "conv_last" in name or "aux" in name ): # heads if "conv_last" in name: A : Tuple =name.replace('conv_last', 'final_convolution' ) if config.upsampler in ["pixelshuffle", "pixelshuffle_aux", "nearest+conv"]: if "conv_before_upsample.0" in name: A : Optional[int] =name.replace('conv_before_upsample.0', 'conv_before_upsample' ) if "upsample.0" in name: A : Optional[int] =name.replace('upsample.0', 'upsample.convolution_0' ) if "upsample.2" in name: A : str =name.replace('upsample.2', 'upsample.convolution_1' ) A : Union[str, Any] ='upsample.' + name elif config.upsampler == "pixelshuffledirect": A : Dict =name.replace('upsample.0.weight', 'upsample.conv.weight' ) A : Tuple =name.replace('upsample.0.bias', 'upsample.conv.bias' ) else: pass else: A : List[Any] ='swin2sr.' + name return name def A__ ( lowercase: Optional[Any], lowercase: Optional[int] ) -> List[Any]: for key in orig_state_dict.copy().keys(): A : Dict =orig_state_dict.pop(lowercase ) if "qkv" in key: A : str =key.split('.' ) A : int =int(key_split[1] ) A : List[str] =int(key_split[4] ) A : int =config.embed_dim if "weight" in key: A : str =val[:dim, :] A : List[str] =val[dim : dim * 2, :] A : Optional[int] =val[-dim:, :] else: A : Optional[int] =val[:dim] A : Dict =val[dim : dim * 2] A : Union[str, Any] =val[-dim:] pass else: A : Union[str, Any] =val return orig_state_dict def A__ ( lowercase: Optional[Any], lowercase: Optional[Any], lowercase: Optional[Any] ) -> Tuple: A : Optional[Any] =get_config(lowercase ) A : Any =SwinaSRForImageSuperResolution(lowercase ) model.eval() A : List[str] =torch.hub.load_state_dict_from_url(lowercase, map_location='cpu' ) A : Tuple =convert_state_dict(lowercase, lowercase ) A , A : List[Any] =model.load_state_dict(lowercase, strict=lowercase ) if len(lowercase ) > 0: raise ValueError('Missing keys when converting: {}'.format(lowercase ) ) for key in unexpected_keys: if not ("relative_position_index" in key or "relative_coords_table" in key or "self_mask" in key): raise ValueError(F'Unexpected key {key} in state_dict' ) # verify values A : Dict ='https://github.com/mv-lab/swin2sr/blob/main/testsets/real-inputs/shanghai.jpg?raw=true' A : int =Image.open(requests.get(lowercase, stream=lowercase ).raw ).convert('RGB' ) A : Union[str, Any] =SwinaSRImageProcessor() # pixel_values = processor(image, return_tensors="pt").pixel_values A : Optional[int] =126 if 'Jpeg' in checkpoint_url else 256 A : Optional[int] =Compose( [ Resize((image_size, image_size) ), ToTensor(), Normalize(mean=[0.4_85, 0.4_56, 0.4_06], std=[0.2_29, 0.2_24, 0.2_25] ), ] ) A : Optional[int] =transforms(lowercase ).unsqueeze(0 ) if config.num_channels == 1: A : List[str] =pixel_values[:, 0, :, :].unsqueeze(1 ) A : List[str] =model(lowercase ) # assert values if "Swin2SR_ClassicalSR_X2_64" in checkpoint_url: A : List[Any] =torch.Size([1, 3, 512, 512] ) A : List[Any] =torch.tensor( [[-0.70_87, -0.71_38, -0.67_21], [-0.83_40, -0.80_95, -0.72_98], [-0.91_49, -0.84_14, -0.79_40]] ) elif "Swin2SR_ClassicalSR_X4_64" in checkpoint_url: A : Tuple =torch.Size([1, 3, 1_024, 1_024] ) A : List[Any] =torch.tensor( [[-0.77_75, -0.81_05, -0.89_33], [-0.77_64, -0.83_56, -0.92_25], [-0.79_76, -0.86_86, -0.95_79]] ) elif "Swin2SR_CompressedSR_X4_48" in checkpoint_url: # TODO values didn't match exactly here A : int =torch.Size([1, 3, 1_024, 1_024] ) A : Optional[Any] =torch.tensor( [[-0.80_35, -0.75_04, -0.74_91], [-0.85_38, -0.81_24, -0.77_82], [-0.88_04, -0.86_51, -0.84_93]] ) elif "Swin2SR_Lightweight_X2_64" in checkpoint_url: A : Optional[int] =torch.Size([1, 3, 512, 512] ) A : str =torch.tensor( [[-0.76_69, -0.86_62, -0.87_67], [-0.88_10, -0.99_62, -0.98_20], [-0.93_40, -1.03_22, -1.11_49]] ) elif "Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR" in checkpoint_url: A : List[Any] =torch.Size([1, 3, 1_024, 1_024] ) A : int =torch.tensor( [[-0.52_38, -0.55_57, -0.63_21], [-0.60_16, -0.59_03, -0.63_91], [-0.62_44, -0.63_34, -0.68_89]] ) assert ( outputs.reconstruction.shape == expected_shape ), F'Shape of reconstruction should be {expected_shape}, but is {outputs.reconstruction.shape}' assert torch.allclose(outputs.reconstruction[0, 0, :3, :3], lowercase, atol=1e-3 ) print('Looks ok!' ) A : Optional[Any] ={ 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth': ( 'swin2SR-classical-sr-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X4_64.pth': ( 'swin2SR-classical-sr-x4-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_CompressedSR_X4_48.pth': ( 'swin2SR-compressed-sr-x4-48' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_Lightweight_X2_64.pth': ( 'swin2SR-lightweight-x2-64' ), 'https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_RealworldSR_X4_64_BSRGAN_PSNR.pth': ( 'swin2SR-realworld-sr-x4-64-bsrgan-psnr' ), } A : Union[str, Any] =url_to_name[checkpoint_url] if pytorch_dump_folder_path is not None: print(F'Saving model {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowercase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) processor.save_pretrained(lowercase ) if push_to_hub: model.push_to_hub(F'caidas/{model_name}' ) processor.push_to_hub(F'caidas/{model_name}' ) if __name__ == "__main__": _lowercase : Any =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://github.com/mv-lab/swin2sr/releases/download/v0.0.1/Swin2SR_ClassicalSR_X2_64.pth''', type=str, help='''URL of the original Swin2SR checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the converted model to the hub.''') _lowercase : Optional[Any] =parser.parse_args() convert_swinasr_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def A__ ( lowercase: Optional[int] ) -> List[str]: A : int =[] embed.append( ( F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight', F'stage{idx}.patch_embed.proj.weight', ) ) embed.append( ( F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias', F'stage{idx}.patch_embed.proj.bias', ) ) embed.append( ( F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight', F'stage{idx}.patch_embed.norm.weight', ) ) embed.append( ( F'cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias', F'stage{idx}.patch_embed.norm.bias', ) ) return embed def A__ ( lowercase: List[Any], lowercase: List[Any] ) -> Any: A : Optional[Any] =[] attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked', F'stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked', F'stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked', F'stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight', F'stage{idx}.blocks.{cnt}.attn.proj_q.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias', F'stage{idx}.blocks.{cnt}.attn.proj_q.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight', F'stage{idx}.blocks.{cnt}.attn.proj_k.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias', F'stage{idx}.blocks.{cnt}.attn.proj_k.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight', F'stage{idx}.blocks.{cnt}.attn.proj_v.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias', F'stage{idx}.blocks.{cnt}.attn.proj_v.bias', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight', F'stage{idx}.blocks.{cnt}.attn.proj.weight', ) ) attention_weights.append( ( F'cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias', F'stage{idx}.blocks.{cnt}.attn.proj.bias', ) ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight', F'stage{idx}.blocks.{cnt}.mlp.fc1.weight') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias', F'stage{idx}.blocks.{cnt}.mlp.fc1.bias') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight', F'stage{idx}.blocks.{cnt}.mlp.fc2.weight') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias', F'stage{idx}.blocks.{cnt}.mlp.fc2.bias') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight', F'stage{idx}.blocks.{cnt}.norm1.weight') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias', F'stage{idx}.blocks.{cnt}.norm1.bias') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight', F'stage{idx}.blocks.{cnt}.norm2.weight') ) attention_weights.append( (F'cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias', F'stage{idx}.blocks.{cnt}.norm2.bias') ) return attention_weights def A__ ( lowercase: int ) -> Dict: A : List[str] =[] token.append((F'cvt.encoder.stages.{idx}.cls_token', 'stage2.cls_token') ) return token def A__ ( ) -> Optional[Any]: A : Tuple =[] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def A__ ( lowercase: List[str], lowercase: Union[str, Any], lowercase: Optional[Any], lowercase: List[Any] ) -> Union[str, Any]: A : List[Any] ='imagenet-1k-id2label.json' A : Optional[Any] =1_000 A : Optional[Any] ='huggingface/label-files' A : Dict =num_labels A : Optional[int] =json.load(open(cached_download(hf_hub_url(lowercase, lowercase, repo_type='dataset' ) ), 'r' ) ) A : Union[str, Any] ={int(lowercase ): v for k, v in idalabel.items()} A : Union[str, Any] =idalabel A : int ={v: k for k, v in idalabel.items()} A : str =CvtConfig(num_labels=lowercase, idalabel=lowercase, labelaid=lowercase ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/', 1 )[-1][4:6] == "13": A : Tuple =[1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/', 1 )[-1][4:6] == "21": A : List[str] =[1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: A : Optional[int] =[2, 2, 20] A : List[str] =[3, 12, 16] A : Tuple =[192, 768, 1_024] A : Optional[int] =CvtForImageClassification(lowercase ) A : List[str] =AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) A : Union[str, Any] =image_size A : int =torch.load(lowercase, map_location=torch.device('cpu' ) ) A : Any =OrderedDict() A : Tuple =[] for idx in range(len(config.depth ) ): if config.cls_token[idx]: A : Optional[Any] =list_of_state_dict + cls_token(lowercase ) A : Optional[int] =list_of_state_dict + embeddings(lowercase ) for cnt in range(config.depth[idx] ): A : Dict =list_of_state_dict + attention(lowercase, lowercase ) A : str =list_of_state_dict + final() for gg in list_of_state_dict: print(lowercase ) for i in range(len(lowercase ) ): A : Dict =original_weights[list_of_state_dict[i][1]] model.load_state_dict(lowercase ) model.save_pretrained(lowercase ) image_processor.save_pretrained(lowercase ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": _lowercase : Optional[int] =argparse.ArgumentParser() parser.add_argument( '''--cvt_model''', default='''cvt-w24''', type=str, help='''Name of the cvt model you\'d like to convert.''', ) parser.add_argument( '''--image_size''', default=3_8_4, type=int, help='''Input Image Size''', ) parser.add_argument( '''--cvt_file_name''', default=R'''cvtmodels\CvT-w24-384x384-IN-22k.pth''', type=str, help='''Input Image Size''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) _lowercase : Union[str, Any] =parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
from typing import List, Optional, Union import numpy as np import torch import torchaudio.compliance.kaldi as ta_kaldi from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging _lowercase : Tuple =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Any = ["input_features", "attention_mask"] def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str=80 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_60_00 , SCREAMING_SNAKE_CASE__ : Dict=80 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> List[str]: super().__init__(feature_size=SCREAMING_SNAKE_CASE__ , sampling_rate=SCREAMING_SNAKE_CASE__ , padding_value=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : List[Any] =num_mel_bins A : Any =do_ceptral_normalize A : Optional[Any] =normalize_means A : List[str] =normalize_vars A : Optional[int] =True def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : np.ndarray , ) -> np.ndarray: A : Union[str, Any] =waveform * (2**15) # Kaldi compliance: 16-bit signed integers A : Union[str, Any] =torch.from_numpy(SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ) A : Any =ta_kaldi.fbank(SCREAMING_SNAKE_CASE__ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate ) return features.numpy() @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[bool] = True , SCREAMING_SNAKE_CASE__ : Optional[bool] = True , SCREAMING_SNAKE_CASE__ : float = 0.0 , ) -> np.ndarray: # make sure we normalize float32 arrays if normalize_means: A : List[str] =x[:input_length].mean(axis=0 ) A : Tuple =np.subtract(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if normalize_vars: A : Optional[int] =x[:input_length].std(axis=0 ) A : Optional[Any] =np.divide(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if input_length < x.shape[0]: A : Tuple =padding_value # make sure array is in float32 A : Dict =x.astype(np.floataa ) return x def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : List[np.ndarray] , SCREAMING_SNAKE_CASE__ : Optional[np.ndarray] = None ) -> List[np.ndarray]: A : List[Any] =attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features] return [ self.utterance_cmvn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.normalize_means , self.normalize_vars , self.padding_value ) for x, n in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ] def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> BatchFeature: if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'The model corresponding to this feature extractor: {self} was trained using a sampling rate of' f' {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with' f' {self.sampling_rate} and not {sampling_rate}.' ) else: logger.warning( 'It is strongly recommended to pass the `sampling_rate` argument to this function. ' 'Failing to do so can result in silent errors that might be hard to debug.' ) A : List[Any] =isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) and len(raw_speech.shape ) > 1 if is_batched_numpy and len(raw_speech.shape ) > 2: raise ValueError(f'Only mono-channel audio is supported for input to {self}' ) A : Optional[int] =is_batched_numpy or ( isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: A : Optional[Any] =[np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) for speech in raw_speech] elif not is_batched and not isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ): A : str =np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) elif isinstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): A : Optional[Any] =raw_speech.astype(np.floataa ) # always return batch if not is_batched: A : Union[str, Any] =[raw_speech] # extract fbank features A : Dict =[self._extract_fbank_features(SCREAMING_SNAKE_CASE__ ) for waveform in raw_speech] # convert into correct format for padding A : int =BatchFeature({'input_features': features} ) A : Optional[int] =self.pad( SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) # make sure list is in array format A : Optional[Any] =padded_inputs.get('input_features' ) if isinstance(input_features[0] , SCREAMING_SNAKE_CASE__ ): A : Union[str, Any] =[np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.floataa ) for feature in input_features] A : str =padded_inputs.get('attention_mask' ) if attention_mask is not None: A : List[str] =[np.asarray(SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) for array in attention_mask] # Utterance-level cepstral mean and variance normalization if self.do_ceptral_normalize: A : int =( np.array(SCREAMING_SNAKE_CASE__ , dtype=np.intaa ) if self._get_padding_strategies(SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) is not PaddingStrategy.DO_NOT_PAD else None ) A : Tuple =self.normalize( padded_inputs['input_features'] , attention_mask=SCREAMING_SNAKE_CASE__ ) if return_tensors is not None: A : int =padded_inputs.convert_to_tensors(SCREAMING_SNAKE_CASE__ ) return padded_inputs
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[Any]: A : List[str] ={ 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 1_28, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 1_42, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } A : List[str] ={ 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 1_28, 'task_specific_params.summarization.min_length': 12, 'task_specific_params.summarization.num_beams': 4, 'task_specific_params.summarization_cnn.length_penalty': 2.0, 'task_specific_params.summarization_cnn.max_length': 1_42, 'task_specific_params.summarization_cnn.min_length': 56, 'task_specific_params.summarization_cnn.num_beams': 4, 'task_specific_params.summarization_xsum.length_penalty': 1.0, 'task_specific_params.summarization_xsum.max_length': 62, 'task_specific_params.summarization_xsum.min_length': 11, 'task_specific_params.summarization_xsum.num_beams': 6, } self.assertEqual(flatten_dict(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: A : str =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , x.transpose() ) ) A : Optional[int] =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : int =np.random.randn(3 , 4 ) A : List[Any] =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) A : Any =np.random.randn(3 , 4 , 5 ) A : Optional[int] =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: A : Optional[Any] =np.random.randn(3 , 4 ) A : List[Any] =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , transpose(SCREAMING_SNAKE_CASE__ ).numpy() ) ) A : Union[str, Any] =np.random.randn(3 , 4 , 5 ) A : List[Any] =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Optional[int]: A : str =np.random.randn(3 , 4 ) A : Tuple =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ ) ) ) ) A : Optional[Any] =np.random.randn(3 , 4 , 5 ) A : Union[str, Any] =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) , np.asarray(transpose(SCREAMING_SNAKE_CASE__ , axes=(1, 2, 0) ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[Any]: A : List[str] =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) A : Union[str, Any] =np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: A : Union[str, Any] =np.random.randn(3 , 4 ) A : List[Any] =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) A : Optional[int] =np.random.randn(3 , 4 , 5 ) A : Any =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[str]: A : str =np.random.randn(3 , 4 ) A : int =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ).numpy() ) ) A : List[Any] =np.random.randn(3 , 4 , 5 ) A : List[str] =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: A : Any =np.random.randn(3 , 4 ) A : List[str] =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (4, 3) ) ) ) ) A : str =np.random.randn(3 , 4 , 5 ) A : Tuple =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) , np.asarray(reshape(SCREAMING_SNAKE_CASE__ , (12, 5) ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[Any]: A : List[str] =np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.squeeze(SCREAMING_SNAKE_CASE__ ) ) ) A : Dict =np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[Any]: A : int =np.random.randn(1 , 3 , 4 ) A : Optional[int] =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) A : Tuple =np.random.randn(1 , 4 , 1 , 5 ) A : Any =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: A : Optional[Any] =np.random.randn(1 , 3 , 4 ) A : Union[str, Any] =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , squeeze(SCREAMING_SNAKE_CASE__ ).numpy() ) ) A : Any =np.random.randn(1 , 4 , 1 , 5 ) A : Optional[Any] =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> int: A : List[str] =np.random.randn(1 , 3 , 4 ) A : int =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ ) ) ) ) A : List[Any] =np.random.randn(1 , 4 , 1 , 5 ) A : Any =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) , np.asarray(squeeze(SCREAMING_SNAKE_CASE__ , axis=2 ) ) ) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: A : Tuple =np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Tuple: A : Union[str, Any] =np.random.randn(3 , 4 ) A : Optional[Any] =torch.tensor(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> str: A : str =np.random.randn(3 , 4 ) A : int =tf.constant(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ).numpy() ) ) @require_flax def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: A : Optional[int] =np.random.randn(3 , 4 ) A : Optional[int] =jnp.array(SCREAMING_SNAKE_CASE__ ) self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) , np.asarray(expand_dims(SCREAMING_SNAKE_CASE__ , axis=1 ) ) ) )
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
from __future__ import annotations _lowercase : Tuple =1.6_0_2_1E-1_9 # units = C def A__ ( lowercase: float, lowercase: float, lowercase: float, ) -> tuple[str, float]: if (conductivity, electron_conc, mobility).count(0 ) != 1: raise ValueError('You cannot supply more or less than 2 values' ) elif conductivity < 0: raise ValueError('Conductivity cannot be negative' ) elif electron_conc < 0: raise ValueError('Electron concentration cannot be negative' ) elif mobility < 0: raise ValueError('mobility cannot be negative' ) elif conductivity == 0: return ( "conductivity", mobility * electron_conc * ELECTRON_CHARGE, ) elif electron_conc == 0: return ( "electron_conc", conductivity / (mobility * ELECTRON_CHARGE), ) else: return ( "mobility", conductivity / (electron_conc * ELECTRON_CHARGE), ) if __name__ == "__main__": import doctest doctest.testmod()
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsรฉ.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
import unittest import numpy as np import torch from diffusers import ScoreSdeVePipeline, ScoreSdeVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: torch.manual_seed(0 ) A : 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') , ) return model def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Dict =self.dummy_uncond_unet A : int =ScoreSdeVeScheduler() A : Union[str, Any] =ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.manual_seed(0 ) A : Dict =sde_ve(num_inference_steps=2 , output_type='numpy' , generator=SCREAMING_SNAKE_CASE__ ).images A : List[Any] =torch.manual_seed(0 ) A : List[str] =sde_ve(num_inference_steps=2 , output_type='numpy' , generator=SCREAMING_SNAKE_CASE__ , return_dict=SCREAMING_SNAKE_CASE__ )[ 0 ] A : List[Any] =image[0, -3:, -3:, -1] A : List[Any] =image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : str =np.array([0.0, 1.0, 0.0, 0.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 SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : int ='google/ncsnpp-church-256' A : Dict =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =ScoreSdeVeScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =ScoreSdeVePipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) sde_ve.to(SCREAMING_SNAKE_CASE__ ) sde_ve.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : List[str] =sde_ve(num_inference_steps=10 , output_type='numpy' , generator=SCREAMING_SNAKE_CASE__ ).images A : Dict =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Dict =np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = (CMStochasticIterativeScheduler,) lowercase : Optional[int] = 10 def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: A : List[str] ={ 'num_train_timesteps': 2_01, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**SCREAMING_SNAKE_CASE__ ) return config def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: A : str =10 A : List[str] =self.get_scheduler_config() A : Any =self.scheduler_classes[0](**SCREAMING_SNAKE_CASE__ ) scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) A : str =scheduler.timesteps[0] A : Tuple =scheduler.timesteps[1] A : Dict =self.dummy_sample A : List[str] =0.1 * sample A : Tuple =scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample A : Dict =scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: for timesteps in [10, 50, 1_00, 10_00]: self.check_over_configs(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: A : Dict =self.scheduler_classes[0] A : Union[str, Any] =self.get_scheduler_config() A : Union[str, Any] =scheduler_class(**SCREAMING_SNAKE_CASE__ ) A : Tuple =1 scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) A : Any =scheduler.timesteps A : Optional[Any] =torch.manual_seed(0 ) A : List[Any] =self.dummy_model() A : Any =self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(SCREAMING_SNAKE_CASE__ ): # 1. scale model input A : Optional[Any] =scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2. predict noise residual A : str =model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 3. predict previous sample x_t-1 A : Optional[Any] =scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample A : Any =pred_prev_sample A : Dict =torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A : Dict =torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def SCREAMING_SNAKE_CASE_ ( self : int ) -> str: A : int =self.scheduler_classes[0] A : str =self.get_scheduler_config() A : Dict =scheduler_class(**SCREAMING_SNAKE_CASE__ ) A : int =[1_06, 0] scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =scheduler.timesteps A : Dict =torch.manual_seed(0 ) A : str =self.dummy_model() A : str =self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input A : Union[str, Any] =scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 2. predict noise residual A : str =model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # 3. predict previous sample x_t-1 A : int =scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).prev_sample A : Union[str, Any] =pred_prev_sample A : int =torch.sum(torch.abs(SCREAMING_SNAKE_CASE__ ) ) A : Dict =torch.mean(torch.abs(SCREAMING_SNAKE_CASE__ ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: A : Union[str, Any] =self.scheduler_classes[0] A : List[str] =self.get_scheduler_config() A : Tuple =scheduler_class(**SCREAMING_SNAKE_CASE__ ) A : List[Any] =[39, 30, 12, 15, 0] with self.assertRaises(SCREAMING_SNAKE_CASE__ , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: A : Optional[int] =self.scheduler_classes[0] A : int =self.get_scheduler_config() A : Any =scheduler_class(**SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =[39, 30, 12, 1, 0] A : Dict =len(SCREAMING_SNAKE_CASE__ ) with self.assertRaises(SCREAMING_SNAKE_CASE__ , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=SCREAMING_SNAKE_CASE__ , timesteps=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[Any]: A : Optional[Any] =self.scheduler_classes[0] A : Tuple =self.get_scheduler_config() A : List[Any] =scheduler_class(**SCREAMING_SNAKE_CASE__ ) A : List[Any] =[scheduler.config.num_train_timesteps] with self.assertRaises( SCREAMING_SNAKE_CASE__ , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=SCREAMING_SNAKE_CASE__ )
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
1
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'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. A : Optional[int] =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: A : str =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) 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 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =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: A : Optional[Any] =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) 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 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).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!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =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] ) ): A : Tuple ='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 A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\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()
661
1
from pathlib import Path import numpy as np from PIL import Image def A__ ( lowercase: np.ndarray ) -> np.ndarray: A , A , A : Dict =rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.29_89 * r + 0.58_70 * g + 0.11_40 * b def A__ ( lowercase: np.ndarray ) -> np.ndarray: return (gray > 127) & (gray <= 255) def A__ ( lowercase: np.ndarray, lowercase: np.ndarray ) -> np.ndarray: A : int =np.zeros_like(lowercase ) A : Optional[int] =np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image A : Optional[int] =image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): A : str =( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() A : List[Any] =int(summation > 0 ) return output if __name__ == "__main__": # read original image _lowercase : Any =Path(__file__).resolve().parent / '''image_data''' / '''lena.jpg''' _lowercase : Tuple =np.array(Image.open(lena_path)) # kernel to be applied _lowercase : Dict =np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) _lowercase : Optional[int] =dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image _lowercase : List[str] =Image.fromarray(output).convert('''RGB''') pil_img.save('''result_dilation.png''')
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) _lowercase : str =logging.getLogger() _lowercase : Optional[int] =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str ) -> Any: os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Tuple ={'source': 'What is love ?', 'target': 'life'} A : Optional[int] ={'train': 12, 'val': 2, 'test': 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: A : List[Any] ='\n'.join([contents[field]] * n_lines[split] ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , f'{split}.{field}' ) , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str = "pytorch" ) -> Optional[int]: A : Tuple =self.get_auto_remove_tmp_dir() A : List[Any] =os.path.join(SCREAMING_SNAKE_CASE__ , 'output' ) A : List[str] =os.path.join(SCREAMING_SNAKE_CASE__ , 'data' ) self._create_dummy_data(data_dir=SCREAMING_SNAKE_CASE__ ) A : int =f'\n --data_dir {data_dir} \\n --output_dir {output_dir} \\n --model_name_or_path facebook/rag-sequence-base \\n --model_type rag_sequence \\n --do_train \\n --do_predict \\n --n_val -1 \\n --val_check_interval 1.0 \\n --train_batch_size 2 \\n --eval_batch_size 1 \\n --max_source_length 25 \\n --max_target_length 25 \\n --val_max_target_length 25 \\n --test_max_target_length 25 \\n --label_smoothing 0.1 \\n --dropout 0.1 \\n --attention_dropout 0.1 \\n --weight_decay 0.001 \\n --adam_epsilon 1e-08 \\n --max_grad_norm 0.1 \\n --lr_scheduler polynomial \\n --learning_rate 3e-04 \\n --num_train_epochs 1 \\n --warmup_steps 4 \\n --gradient_accumulation_steps 1 \\n --distributed-port 8787 \\n --use_dummy_dataset 1 \\n --distributed_retriever {distributed_retriever} \\n '.split() if gpus > 0: testargs.append(f'--gpus={gpus}' ) if is_apex_available(): testargs.append('--fp16' ) else: testargs.append('--gpus=0' ) testargs.append('--distributed_backend=ddp_cpu' ) testargs.append('--num_processes=2' ) A : str =[sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) A : Optional[int] =os.path.join(SCREAMING_SNAKE_CASE__ , 'metrics.json' ) with open(SCREAMING_SNAKE_CASE__ ) as f: A : int =json.load(SCREAMING_SNAKE_CASE__ ) return result @require_torch_gpu def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: A : Any =self._run_finetune(gpus=1 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_multi_gpu def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: A : Union[str, Any] =self._run_finetune(gpus=2 ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_gpu @require_ray def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Tuple =self._run_finetune(gpus=1 , distributed_retriever='ray' ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 ) @require_torch_multi_gpu @require_ray def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> int: A : str =self._run_finetune(gpus=1 , distributed_retriever='ray' ) self.assertGreaterEqual(result['test'][0]['test_avg_em'] , 0.2 )
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from ..utils import cached_file # docstyle-ignore _lowercase : Optional[Any] =''' Human: <<task>> Assistant: ''' _lowercase : Union[str, Any] ='''huggingface-tools/default-prompts''' _lowercase : Any ={'''chat''': '''chat_prompt_template.txt''', '''run''': '''run_prompt_template.txt'''} def A__ ( lowercase: List[Any], lowercase: Dict, lowercase: str="run" ) -> List[Any]: if prompt_or_repo_id is None: A : List[str] =DEFAULT_PROMPTS_REPO # prompt is considered a repo ID when it does not contain any kind of space if re.search('\\s', lowercase ) is not None: return prompt_or_repo_id A : str =cached_file( lowercase, PROMPT_FILES[mode], repo_type='dataset', user_agent={'agent': agent_name} ) with open(lowercase, 'r', encoding='utf-8' ) as f: return f.read()
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
def A__ ( lowercase: int, lowercase: int ) -> int: return int(input_a == input_a == 0 ) def A__ ( ) -> None: print('Truth Table of NOR Gate:' ) print('| Input 1 | Input 2 | Output |' ) print(F'| 0 | 0 | {nor_gate(0, 0 )} |' ) print(F'| 0 | 1 | {nor_gate(0, 1 )} |' ) print(F'| 1 | 0 | {nor_gate(1, 0 )} |' ) print(F'| 1 | 1 | {nor_gate(1, 1 )} |' ) if __name__ == "__main__": import doctest doctest.testmod() main()
661
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Any =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging _lowercase : Union[str, Any] =logging.get_logger(__name__) _lowercase : Any ='''โ–''' _lowercase : Optional[int] ={ '''vocab_file''': '''vocab.json''', '''spm_file''': '''sentencepiece.bpe.model''', '''tokenizer_config_file''': '''tokenizer_config.json''', } _lowercase : Any ={ '''vocab_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json''', }, '''spm_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model''', }, '''tokenizer_config_file''': { '''facebook/m2m100_418M''': '''https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json''', '''facebook/m2m100_1.2B''': '''https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json''', }, } _lowercase : Union[str, Any] ={ '''facebook/m2m100_418M''': 1_0_2_4, } # fmt: off _lowercase : List[str] ={ '''m2m100''': ['''af''', '''am''', '''ar''', '''ast''', '''az''', '''ba''', '''be''', '''bg''', '''bn''', '''br''', '''bs''', '''ca''', '''ceb''', '''cs''', '''cy''', '''da''', '''de''', '''el''', '''en''', '''es''', '''et''', '''fa''', '''ff''', '''fi''', '''fr''', '''fy''', '''ga''', '''gd''', '''gl''', '''gu''', '''ha''', '''he''', '''hi''', '''hr''', '''ht''', '''hu''', '''hy''', '''id''', '''ig''', '''ilo''', '''is''', '''it''', '''ja''', '''jv''', '''ka''', '''kk''', '''km''', '''kn''', '''ko''', '''lb''', '''lg''', '''ln''', '''lo''', '''lt''', '''lv''', '''mg''', '''mk''', '''ml''', '''mn''', '''mr''', '''ms''', '''my''', '''ne''', '''nl''', '''no''', '''ns''', '''oc''', '''or''', '''pa''', '''pl''', '''ps''', '''pt''', '''ro''', '''ru''', '''sd''', '''si''', '''sk''', '''sl''', '''so''', '''sq''', '''sr''', '''ss''', '''su''', '''sv''', '''sw''', '''ta''', '''th''', '''tl''', '''tn''', '''tr''', '''uk''', '''ur''', '''uz''', '''vi''', '''wo''', '''xh''', '''yi''', '''yo''', '''zh''', '''zu'''], '''wmt21''': ['''en''', '''ha''', '''is''', '''ja''', '''cs''', '''ru''', '''zh''', '''de'''] } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : List[Any] = VOCAB_FILES_NAMES lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase : str = ["input_ids", "attention_mask"] lowercase : List[int] = [] lowercase : List[int] = [] def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : Optional[int]="<s>" , SCREAMING_SNAKE_CASE__ : List[Any]="</s>" , SCREAMING_SNAKE_CASE__ : Tuple="</s>" , SCREAMING_SNAKE_CASE__ : List[str]="<pad>" , SCREAMING_SNAKE_CASE__ : List[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : List[Any]="m2m100" , SCREAMING_SNAKE_CASE__ : Optional[Dict[str, Any]] = None , SCREAMING_SNAKE_CASE__ : int=8 , **SCREAMING_SNAKE_CASE__ : Optional[Any] , ) -> None: A : Optional[Any] ={} if sp_model_kwargs is None else sp_model_kwargs A : Any =language_codes A : int =FAIRSEQ_LANGUAGE_CODES[language_codes] A : Dict ={lang_code: f'__{lang_code}__' for lang_code in fairseq_language_code} A : Optional[int] =kwargs.get('additional_special_tokens' , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(SCREAMING_SNAKE_CASE__ ) for lang_code in fairseq_language_code if self.get_lang_token(SCREAMING_SNAKE_CASE__ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , language_codes=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) A : Dict =vocab_file A : List[str] =load_json(SCREAMING_SNAKE_CASE__ ) A : List[str] ={v: k for k, v in self.encoder.items()} A : Dict =spm_file A : Any =load_spm(SCREAMING_SNAKE_CASE__ , self.sp_model_kwargs ) A : Optional[Any] =len(self.encoder ) A : List[str] ={ self.get_lang_token(SCREAMING_SNAKE_CASE__ ): self.encoder_size + i for i, lang_code in enumerate(SCREAMING_SNAKE_CASE__ ) } A : int ={lang_code: self.encoder_size + i for i, lang_code in enumerate(SCREAMING_SNAKE_CASE__ )} A : List[Any] ={v: k for k, v in self.lang_token_to_id.items()} A : str =src_lang if src_lang is not None else 'en' A : Optional[int] =tgt_lang A : int =self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) A : Optional[Any] =num_madeup_words @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> int: return len(self.encoder ) + len(self.lang_token_to_id ) @property def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: return self._src_lang @src_lang.setter def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> None: A : Tuple =new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Any: if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(SCREAMING_SNAKE_CASE__ , self.encoder[self.unk_token] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> str: if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(SCREAMING_SNAKE_CASE__ , self.unk_token ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Dict ) -> Union[str, Any]: A : int =[] A : Tuple ='' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) + token A : Tuple =[] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None , SCREAMING_SNAKE_CASE__ : bool = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =[1] * len(self.prefix_tokens ) A : Any =[1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE__ )) + suffix_ones return prefix_ones + ([0] * len(SCREAMING_SNAKE_CASE__ )) + ([0] * len(SCREAMING_SNAKE_CASE__ )) + suffix_ones def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[int] , SCREAMING_SNAKE_CASE__ : Optional[List[int]] = None ) -> List[int]: if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : List[Any] ={self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[Any] ) -> Dict: A : str =self.__dict__.copy() A : List[Any] =None return state def __setstate__( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict ) -> None: A : Dict =d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): A : List[Any] ={} A : Any =load_spm(self.spm_file , self.sp_model_kwargs ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[str] = None ) -> Tuple[str]: A : int =Path(SCREAMING_SNAKE_CASE__ ) if not save_dir.is_dir(): raise OSError(f'{save_directory} should be a directory' ) A : Dict =save_dir / ( (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file'] ) A : str =save_dir / ( (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file'] ) save_json(self.encoder , SCREAMING_SNAKE_CASE__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.spm_file ): with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as fi: A : Union[str, Any] =self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (str(SCREAMING_SNAKE_CASE__ ), str(SCREAMING_SNAKE_CASE__ )) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str = "en" , SCREAMING_SNAKE_CASE__ : Optional[List[str]] = None , SCREAMING_SNAKE_CASE__ : str = "ro" , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> BatchEncoding: A : Any =src_lang A : List[Any] =tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[str] , SCREAMING_SNAKE_CASE__ : Optional[str] , **SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) A : Any =src_lang A : List[str] =self(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Optional[int] =self.get_lang_id(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tgt_lang_id return inputs def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[int]: self.set_src_lang_special_tokens(self.src_lang ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: self.set_tgt_lang_special_tokens(self.tgt_lang ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> None: A : List[Any] =self.get_lang_token(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.lang_token_to_id[lang_token] A : Dict =[self.cur_lang_id] A : Tuple =[self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> None: A : Optional[Any] =self.get_lang_token(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =self.lang_token_to_id[lang_token] A : Union[str, Any] =[self.cur_lang_id] A : Dict =[self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> str: return self.lang_code_to_token[lang] def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : str ) -> int: A : Tuple =self.get_lang_token(SCREAMING_SNAKE_CASE__ ) return self.lang_token_to_id[lang_token] def A__ ( lowercase: str, lowercase: Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: A : str =sentencepiece.SentencePieceProcessor(**lowercase ) spm.Load(str(lowercase ) ) return spm def A__ ( lowercase: str ) -> Union[Dict, List]: with open(lowercase, 'r' ) as f: return json.load(lowercase ) def A__ ( lowercase: List[str], lowercase: str ) -> None: with open(lowercase, 'w' ) as f: json.dump(lowercase, lowercase, indent=2 )
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin _lowercase : int =get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right _lowercase : Union[str, Any] =2_5_0_0_0_4 _lowercase : Any =2_5_0_0_2_0 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Any = MBartaaTokenizer lowercase : Union[str, Any] = MBartaaTokenizerFast lowercase : Dict = True lowercase : str = True def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> str: super().setUp() # We have a SentencePiece fixture for testing A : str =MBartaaTokenizer(SCREAMING_SNAKE_CASE__ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> int: A : Optional[int] ='<s>' A : str =0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> int: A : Optional[Any] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_54 ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: self.assertEqual(self.get_tokenizer().vocab_size , 10_54 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Tuple: A : List[Any] =MBartaaTokenizer(SCREAMING_SNAKE_CASE__ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : List[str] =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.'] , ) A : Dict =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) A : Optional[int] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> str: # fmt: off A : Union[str, Any] ={'input_ids': [[25_00_04, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [25_00_04, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [25_00_04, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart50', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : Dict =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Tuple =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[Any] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : Dict =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Union[str, Any] =tempfile.mkdtemp() A : Any =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : Optional[Any] =tempfile.mkdtemp() A : List[Any] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[str] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : List[str] = "facebook/mbart-large-50-one-to-many-mmt" lowercase : int = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] lowercase : str = [ "ลžeful ONU declarฤƒ cฤƒ nu existฤƒ o soluลฃie militarฤƒ รฎn Siria", "Secretarul General Ban Ki-moon declarฤƒ cฤƒ rฤƒspunsul sฤƒu la intensificarea sprijinului militar al Rusiei" " pentru Siria este cฤƒ \"nu existฤƒ o soluลฃie militarฤƒ\" la conflictul de aproape cinci ani ลŸi cฤƒ noi arme nu vor" " face decรขt sฤƒ รฎnrฤƒutฤƒลฃeascฤƒ violenลฃele ลŸi mizeria pentru milioane de oameni.", ] lowercase : str = [EN_CODE, 8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2] @classmethod def SCREAMING_SNAKE_CASE_ ( cls : int ) -> Dict: A : MBartaaTokenizer =MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) A : Any =1 return cls def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 25_00_20 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 25_00_38 ) def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Optional[Any] =self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: self.assertIn(SCREAMING_SNAKE_CASE__ , self.tokenizer.all_special_ids ) A : List[str] =[RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] A : Any =self.tokenizer.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) A : str =self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotIn(self.tokenizer.eos_token , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Any: A : Optional[int] =['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , SCREAMING_SNAKE_CASE__ ) A : Tuple =10 A : List[Any] =self.tokenizer(SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ ).input_ids[0] self.assertEqual(ids[0] , SCREAMING_SNAKE_CASE__ ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [25_00_53, 25_00_01] ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : Dict =tempfile.mkdtemp() A : str =self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =MBartaaTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , SCREAMING_SNAKE_CASE__ ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Dict: A : Optional[int] =self.tokenizer(self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) A : str =shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def SCREAMING_SNAKE_CASE_ ( self : str ) -> Any: A : Union[str, Any] =self.tokenizer( self.src_text , text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) A : List[str] =shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) A : Dict =batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , SCREAMING_SNAKE_CASE__ ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: A : int =self.tokenizer(self.src_text , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=3 , return_tensors='pt' ) A : Tuple =self.tokenizer( text_target=self.tgt_text , padding=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , max_length=10 , return_tensors='pt' ) A : Tuple =targets['input_ids'] A : Any =shift_tokens_right(SCREAMING_SNAKE_CASE__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: A : Dict =self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(SCREAMING_SNAKE_CASE__ ) , { # en_XX, A, test, EOS 'input_ids': [[25_00_04, 62, 30_34, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_00_01, } , )
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def A__ ( lowercase: int, lowercase: str ) -> Dict: assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Dict, lowercase: Tuple, lowercase: str ) -> str: A : Any =tmp_path / 'cache' A : Dict ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : Dict =JsonDatasetReader(lowercase, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Any, lowercase: Union[str, Any] ) -> Tuple: A : Tuple =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : Optional[Any] =features.copy() if features else default_expected_features A : Union[str, Any] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : str =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ], ) def A__ ( lowercase: Optional[int], lowercase: str, lowercase: Dict ) -> Optional[int]: A : int =tmp_path / 'cache' A : Tuple ={'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} A : int =features.copy() if features else default_expected_features A : str =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def A__ ( lowercase: Optional[Any], lowercase: str ) -> Tuple: # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} A : str ={'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} A : Dict =features.copy() A : List[str] =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : int =tmp_path / 'cache' A : Optional[int] =JsonDatasetReader(lowercase, features=lowercase, cache_dir=lowercase ).read() assert isinstance(lowercase, lowercase ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Union[str, Any], lowercase: Any, lowercase: str ) -> Optional[Any]: A : Optional[int] =tmp_path / 'cache' A : Optional[Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =JsonDatasetReader(lowercase, cache_dir=lowercase, split=lowercase ).read() _check_json_dataset(lowercase, lowercase ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type', [str, list] ) def A__ ( lowercase: Optional[Any], lowercase: int, lowercase: Union[str, Any] ) -> List[Any]: if issubclass(lowercase, lowercase ): A : int =jsonl_path elif issubclass(lowercase, lowercase ): A : Any =[jsonl_path] A : Optional[Any] =tmp_path / 'cache' A : Tuple ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[str] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_dataset(lowercase, lowercase ) def A__ ( lowercase: List[str], lowercase: Tuple, lowercase: Optional[Any]=("train",) ) -> Tuple: assert isinstance(lowercase, lowercase ) for split in splits: A : List[str] =dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory', [False, True] ) def A__ ( lowercase: Tuple, lowercase: Optional[int], lowercase: Any ) -> str: A : List[str] =tmp_path / 'cache' A : Union[str, Any] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): A : str =JsonDatasetReader({'train': jsonl_path}, cache_dir=lowercase, keep_in_memory=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize( 'features', [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ], ) def A__ ( lowercase: Optional[int], lowercase: Optional[int], lowercase: Optional[int] ) -> Tuple: A : Any =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : str =features.copy() if features else default_expected_features A : Dict =( Features({feature: Value(lowercase ) for feature, dtype in features.items()} ) if features is not None else None ) A : Optional[Any] =JsonDatasetReader({'train': jsonl_path}, features=lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase ) @pytest.mark.parametrize('split', [None, NamedSplit('train' ), 'train', 'test'] ) def A__ ( lowercase: Any, lowercase: List[Any], lowercase: List[Any] ) -> Tuple: if split: A : Optional[int] ={split: jsonl_path} else: A : Dict ='train' A : Optional[Any] ={'train': jsonl_path, 'test': jsonl_path} A : Tuple =tmp_path / 'cache' A : List[str] ={'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} A : List[Any] =JsonDatasetReader(lowercase, cache_dir=lowercase ).read() _check_json_datasetdict(lowercase, lowercase, splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def A__ ( lowercase: List[Any] ) -> Tuple: return json.load(lowercase ) def A__ ( lowercase: List[Any] ) -> Tuple: return [json.loads(lowercase ) for line in buffer] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ ).write() buffer.seek(0 ) A : Any =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : int =load_json_function(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert isinstance(exported_content[0] , SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[Any]: with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , lines=SCREAMING_SNAKE_CASE__ , orient=SCREAMING_SNAKE_CASE__ , num_proc=2 ).write() buffer.seek(0 ) A : List[Any] =load_json(SCREAMING_SNAKE_CASE__ ) assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(SCREAMING_SNAKE_CASE__ , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(SCREAMING_SNAKE_CASE__ ) == 10 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: with pytest.raises(SCREAMING_SNAKE_CASE__ ): with io.BytesIO() as buffer: JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: A : Union[str, Any] =tmp_path_factory.mktemp('data' ) / f'test.json.{extension}' A : Union[str, Any] =str(shared_datadir / f'test_file.json.{extension}' ) JsonDatasetWriter(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , compression=SCREAMING_SNAKE_CASE__ ).write() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : str =f.read() with fsspec.open(SCREAMING_SNAKE_CASE__ , 'rb' , compression='infer' ) as f: A : List[str] =f.read() assert exported_content == original_content
661
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowercase : List[str] ={ '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : str =[ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowercase : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
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 SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Optional[int] = DDIMPipeline lowercase : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS lowercase : Optional[Any] = PipelineTesterMixin.required_optional_params - { "num_images_per_prompt", "latents", "callback", "callback_steps", } lowercase : Optional[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS lowercase : Union[str, Any] = False def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) A : str =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') , ) A : Optional[int] =DDIMScheduler() A : Optional[Any] ={'unet': unet, 'scheduler': scheduler} return components def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : List[Any]=0 ) -> Any: if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ): A : List[Any] =torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A : Union[str, Any] =torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A : Optional[int] ={ 'batch_size': 1, 'generator': generator, 'num_inference_steps': 2, 'output_type': 'numpy', } return inputs def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: A : Union[str, Any] ='cpu' A : Tuple =self.get_dummy_components() A : Union[str, Any] =self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : str =self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) A : str =pipe(**SCREAMING_SNAKE_CASE__ ).images A : Optional[Any] =image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) A : Optional[Any] =np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) A : str =np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1e-3 ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> Dict: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: super().test_save_load_local(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Any ='google/ddpm-cifar10-32' A : Optional[int] =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMScheduler() A : int =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddim.to(SCREAMING_SNAKE_CASE__ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Dict =torch.manual_seed(0 ) A : Optional[Any] =ddim(generator=SCREAMING_SNAKE_CASE__ , eta=0.0 , output_type='numpy' ).images A : str =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A : Tuple =np.array([0.1_7_2_3, 0.1_6_1_7, 0.1_6_0_0, 0.1_6_2_6, 0.1_4_9_7, 0.1_5_1_3, 0.1_5_0_5, 0.1_4_4_2, 0.1_4_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Optional[int] ='google/ddpm-ema-bedroom-256' A : str =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : str =DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =DDIMPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) ddpm.to(SCREAMING_SNAKE_CASE__ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A : Any =torch.manual_seed(0 ) A : Optional[int] =ddpm(generator=SCREAMING_SNAKE_CASE__ , output_type='numpy' ).images A : List[Any] =image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A : Optional[int] =np.array([0.0_0_6_0, 0.0_2_0_1, 0.0_3_4_4, 0.0_0_2_4, 0.0_0_1_8, 0.0_0_0_2, 0.0_0_2_2, 0.0_0_0_0, 0.0_0_6_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
661
1
import heapq import sys import numpy as np _lowercase : str =tuple[int, int] class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] ) -> int: A : int =[] A : Optional[Any] =set() def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: if not self.empty(): return self.elements[0][0] else: return float('inf' ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> str: return len(self.elements ) == 0 def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int ) -> 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) A : str =[] ((A) , (A)) : Dict =heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((A) , (A)) : int =heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> str: if item in self.set: self.set.remove(SCREAMING_SNAKE_CASE__ ) A : str =[] ((A) , (A)) : List[str] =heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((A) , (A)) : List[Any] =heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[Any]: return self.elements[0][1] def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: ((A) , (A)) : Any =heapq.heappop(self.elements ) self.set.remove(SCREAMING_SNAKE_CASE__ ) return (priority, item) def A__ ( lowercase: TPos, lowercase: TPos ) -> Union[str, Any]: # euclidean distance A : Union[str, Any] =np.array(lowercase ) A : Tuple =np.array(lowercase ) return np.linalg.norm(a - b ) def A__ ( lowercase: TPos, lowercase: TPos ) -> str: # integer division by time variable return consistent_heuristic(lowercase, lowercase ) // t def A__ ( lowercase: TPos, lowercase: TPos ) -> int: # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def A__ ( lowercase: TPos, lowercase: int, lowercase: TPos, lowercase: dict[TPos, float] ) -> List[str]: A : int =g_function[start] + Wa * heuristics[i](lowercase, lowercase ) return ans def A__ ( lowercase: List[Any], lowercase: str, lowercase: Optional[int] ) -> Tuple: A : Any =np.chararray((n, n) ) for i in range(lowercase ): for j in range(lowercase ): A : Optional[int] ='*' for i in range(lowercase ): for j in range(lowercase ): if (j, (n - 1) - i) in blocks: A : Any ='#' A : Union[str, Any] ='-' A : str =back_pointer[goal] while x != start: ((A) , (A)) : List[str] =x # print(x) A : str ='-' A : Dict =back_pointer[x] A : Any ='-' for i in range(lowercase ): for j in range(lowercase ): 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:-' ) A : Union[str, Any] =back_pointer[goal] while x != start: print(lowercase, end=' ' ) A : str =back_pointer[x] print(lowercase ) sys.exit() def A__ ( lowercase: TPos ) -> str: 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__ ( lowercase: Union[str, Any], lowercase: Union[str, Any], lowercase: Tuple, lowercase: Dict, lowercase: List[Any], lowercase: List[Any], lowercase: str, lowercase: str, ) -> Optional[int]: for itera in range(lowercase ): open_list[itera].remove_element(lowercase ) # print("s", s) # print("j", j) ((A) , (A)) : Dict =s A : Dict =(x - 1, y) A : Union[str, Any] =(x + 1, y) A : List[str] =(x, y + 1) A : int =(x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(lowercase ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(lowercase ) A : Union[str, Any] =-1 A : Union[str, Any] =float('inf' ) if valid(lowercase ) and g_function[neighbours] > g_function[s] + 1: A : Optional[int] =g_function[s] + 1 A : List[str] =s if neighbours not in close_list_anchor: open_list[0].put(lowercase, key(lowercase, 0, lowercase, lowercase ) ) if neighbours not in close_list_inad: for var in range(1, lowercase ): if key(lowercase, lowercase, lowercase, lowercase ) <= Wa * key( lowercase, 0, lowercase, lowercase ): open_list[j].put( lowercase, key(lowercase, lowercase, lowercase, lowercase ) ) def A__ ( ) -> Dict: A : Dict =[] 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 _lowercase : str ={0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowercase : Dict =[ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (1_0, 1), (1_1, 1), (1_2, 1), (1_3, 1), (1_4, 1), (1_5, 1), (1_6, 1), (1_7, 1), (1_8, 1), (1_9, 1), ] _lowercase : int =make_common_ground() _lowercase : List[str] =blocks_blk # hyper parameters _lowercase : Union[str, Any] =1 _lowercase : Any =1 _lowercase : str =2_0 _lowercase : Dict =3 # one consistent and two other inconsistent # start and end destination _lowercase : Dict =(0, 0) _lowercase : str =(n - 1, n - 1) _lowercase : Tuple =1 def A__ ( lowercase: TPos, lowercase: TPos, lowercase: int ) -> Union[str, Any]: A : int ={start: 0, goal: float('inf' )} A : str ={start: -1, goal: -1} A : Union[str, Any] =[] A : List[str] =set() for i in range(lowercase ): open_list.append(PriorityQueue() ) open_list[i].put(lowercase, key(lowercase, lowercase, lowercase, lowercase ) ) A : list[int] =[] A : list[int] =[] while open_list[0].minkey() < float('inf' ): for i in range(1, lowercase ): # 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(lowercase, lowercase, lowercase ) else: A , A : str =open_list[i].top_show() visited.add(lowercase ) expand_state( lowercase, lowercase, lowercase, lowercase, lowercase, lowercase, lowercase, lowercase, ) close_list_inad.append(lowercase ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float('inf' ): do_something(lowercase, lowercase, lowercase ) else: A : str =open_list[0].top_show() visited.add(lowercase ) expand_state( lowercase, 0, lowercase, lowercase, lowercase, lowercase, lowercase, lowercase, ) close_list_anchor.append(lowercase ) print('No path found to goal' ) print() for i in range(n - 1, -1, -1 ): for j in range(lowercase ): 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)
661
import shutil import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_tf_cross_test, require_tf, require_torch, require_torchvision, require_vision, ) from transformers.utils import is_tf_available, is_torch_available, is_vision_available if is_vision_available(): from PIL import Image from transformers import AutoProcessor, SamImageProcessor, SamProcessor if is_torch_available(): import torch if is_tf_available(): import tensorflow as tf @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Union[str, Any]: A : Dict =tempfile.mkdtemp() A : int =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[int]: A : str =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Optional[int] =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : Optional[int] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : str =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Union[str, Any] =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =self.get_image_processor() A : Optional[Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Dict =self.prepare_image_inputs() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : Optional[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop original_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_torch def SCREAMING_SNAKE_CASE_ ( self : int ) -> Any: A : str =self.get_image_processor() A : Union[str, Any] =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : str =[torch.ones((1, 3, 5, 5) )] A : Optional[Any] =[[17_64, 26_46]] A : List[Any] =[[6_83, 10_24]] A : Union[str, Any] =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , torch.tensor(SCREAMING_SNAKE_CASE__ ) , torch.tensor(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : str =[np.ones((1, 3, 5, 5) )] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(SCREAMING_SNAKE_CASE__ ): A : Any =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) ) @require_vision @require_tf class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> str: A : Tuple =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Union[str, Any] =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : str ) -> List[str]: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: A : Optional[Any] =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Any =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] =SamProcessor(image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) A : Optional[Any] =self.get_image_processor(do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) A : Dict =SamProcessor.from_pretrained(self.tmpdirname , do_normalize=SCREAMING_SNAKE_CASE__ , padding_value=1.0 ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Any =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : Tuple =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='np' ) A : List[Any] =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) input_feat_extract.pop('original_sizes' ) # pop original_sizes as it is popped in the processor input_feat_extract.pop('reshaped_input_sizes' ) # pop reshaped_input_sizes as it is popped in the processor for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) @require_tf def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: A : int =self.get_image_processor() A : Any =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =[tf.ones((1, 3, 5, 5) )] A : Tuple =[[17_64, 26_46]] A : Union[str, Any] =[[6_83, 10_24]] A : int =processor.post_process_masks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : List[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' , ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) # should also work with np A : Any =[np.ones((1, 3, 5, 5) )] A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) ) A : Any =[[1, 0], [0, 1]] with self.assertRaises(tf.errors.InvalidArgumentError ): A : List[str] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , np.array(SCREAMING_SNAKE_CASE__ ) , np.array(SCREAMING_SNAKE_CASE__ ) , return_tensors='tf' ) @require_vision @require_torchvision class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Union[str, Any]: A : Optional[int] =tempfile.mkdtemp() A : Union[str, Any] =SamImageProcessor() A : Dict =SamProcessor(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int , **SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ).image_processor def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Any: shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Tuple: A : Any =[np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] A : Tuple =[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE__ , 0 , -1 ) ) for x in image_inputs] return image_inputs @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : Optional[Any] =self.get_image_processor() A : Dict =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa ) A : Optional[int] =[tf.convert_to_tensor(SCREAMING_SNAKE_CASE__ )] A : Union[str, Any] =[torch.tensor(SCREAMING_SNAKE_CASE__ )] A : int =[[17_64, 26_46]] A : int =[[6_83, 10_24]] A : Dict =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='tf' ) A : Optional[Any] =processor.post_process_masks( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) ) @is_pt_tf_cross_test def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Union[str, Any] =self.get_image_processor() A : int =SamProcessor(image_processor=SCREAMING_SNAKE_CASE__ ) A : int =self.prepare_image_inputs() A : List[Any] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Tuple =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='pt' )['pixel_values'].numpy() A : Optional[int] =image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() A : Dict =processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='tf' )['pixel_values'].numpy() self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(np.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) )
661
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _lowercase : str ={ '''configuration_pix2struct''': [ '''PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''Pix2StructConfig''', '''Pix2StructTextConfig''', '''Pix2StructVisionConfig''', ], '''processing_pix2struct''': ['''Pix2StructProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : int =['''Pix2StructImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowercase : Any =[ '''PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''Pix2StructPreTrainedModel''', '''Pix2StructForConditionalGeneration''', '''Pix2StructVisionModel''', '''Pix2StructTextModel''', ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys _lowercase : Any =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
661
import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict import requests from slack_sdk import WebClient _lowercase : Optional[Any] =WebClient(token=os.environ['''CI_SLACK_BOT_TOKEN''']) def A__ ( lowercase: Optional[int] ) -> Optional[int]: A : str =test_results.split(' ' ) A : List[str] =0 A : Tuple =0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. A : List[str] =expressions[-2] if '=' in expressions[-1] else expressions[-1] for i, expression in enumerate(lowercase ): if "failed" in expression: failed += int(expressions[i - 1] ) if "passed" in expression: success += int(expressions[i - 1] ) return failed, success, time_spent def A__ ( lowercase: List[Any] ) -> str: A : Union[str, Any] ={} A : Optional[Any] =None A : Union[str, Any] =False for line in failures_short_lines.split('\n' ): if re.search(r'_ \[doctest\]', lowercase ): A : List[Any] =True A : Any =line.split(' ' )[2] elif in_error and not line.split(' ' )[0].isdigit(): A : Dict =line A : List[str] =False return failures class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict ) -> List[str]: A : Tuple =title A : Dict =doc_test_results['time_spent'].split(',' )[0] A : Union[str, Any] =doc_test_results['success'] A : Any =doc_test_results['failures'] A : Optional[Any] =self.n_success + self.n_failures # Failures and success of the modeling tests A : Union[str, Any] =doc_test_results @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> str: A : Any =[self._time_spent] A : List[str] =0 for time in time_spent: A : List[Any] =time.split(':' ) # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(SCREAMING_SNAKE_CASE__ ) == 1: A : List[str] =[0, 0, time_parts[0]] A , A , A : Tuple =int(time_parts[0] ), int(time_parts[1] ), float(time_parts[2] ) total_secs += hours * 36_00 + minutes * 60 + seconds A , A , A : str =total_secs // 36_00, (total_secs % 36_00) // 60, total_secs % 60 return f'{int(SCREAMING_SNAKE_CASE__ )}h{int(SCREAMING_SNAKE_CASE__ )}m{int(SCREAMING_SNAKE_CASE__ )}s' @property def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f'๐ŸŒž There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.', "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f'There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in' f' {self.time}.' ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Dict: A : Tuple =40 A : Optional[Any] ={k: v['failed'] for k, v in doc_test_results.items() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )} A : Any ='' for category, failures in category_failures.items(): if len(SCREAMING_SNAKE_CASE__ ) == 0: continue if report != "": report += "\n\n" report += f'*{category} failures*:'.ljust(line_length // 2 ).rjust(line_length // 2 ) + "\n" report += "`" report += "`\n`".join(SCREAMING_SNAKE_CASE__ ) report += "`" return { "type": "section", "text": { "type": "mrkdwn", "text": f'The following examples had failures:\n\n\n{report}\n', }, } @property def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Optional[int] =[self.header] if self.n_failures > 0: blocks.append(self.failures ) if self.n_failures > 0: blocks.extend([self.category_failures] ) if self.n_failures == 0: blocks.append(self.no_failures ) return json.dumps(SCREAMING_SNAKE_CASE__ ) @staticmethod def SCREAMING_SNAKE_CASE_ ( ) -> Optional[Any]: A : Tuple =[ { 'type': 'section', 'text': { 'type': 'plain_text', 'text': 'There was an issue running the tests.', }, 'accessory': { 'type': 'button', 'text': {'type': 'plain_text', 'text': 'Check Action results', 'emoji': True}, 'url': f'https://github.com/huggingface/transformers/actions/runs/{os.environ["GITHUB_RUN_ID"]}', }, } ] print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(SCREAMING_SNAKE_CASE__ )} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text='There was an issue running the tests.' , blocks=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[int]: print('Sending the following payload' ) print(json.dumps({'blocks': json.loads(self.payload )} ) ) A : Any =f'{self.n_failures} failures out of {self.n_tests} tests,' if self.n_failures else 'All tests passed.' A : Dict =client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , blocks=self.payload , text=SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: A : List[str] ='' for key, value in failures.items(): A : Any =value[:2_00] + ' [Truncated]' if len(SCREAMING_SNAKE_CASE__ ) > 2_50 else value failures_text += f'*{key}*\n_{value}_\n\n' A : Union[str, Any] =job_name A : Any ={'type': 'section', 'text': {'type': 'mrkdwn', 'text': text}} if job_link is not None: A : int ={ 'type': 'button', 'text': {'type': 'plain_text', 'text': 'GitHub Action job', 'emoji': True}, 'url': job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failures_text}}, ] def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: if self.thread_ts is None: raise ValueError('Can only post reply if a post has been made.' ) A : Union[str, Any] =self.doc_test_results.pop('job_link' ) self.doc_test_results.pop('failures' ) self.doc_test_results.pop('success' ) self.doc_test_results.pop('time_spent' ) A : Union[str, Any] =sorted(self.doc_test_results.items() , key=lambda SCREAMING_SNAKE_CASE__ : t[0] ) for job, job_result in sorted_dict: if len(job_result['failures'] ): A : Any =f'*Num failures* :{len(job_result["failed"] )} \n' A : List[Any] =job_result['failures'] A : Any =self.get_reply_blocks(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , text=SCREAMING_SNAKE_CASE__ ) print('Sending the following reply' ) print(json.dumps({'blocks': blocks} ) ) client.chat_postMessage( channel=os.environ['CI_SLACK_CHANNEL_ID_DAILY'] , text=f'Results for {job}' , blocks=SCREAMING_SNAKE_CASE__ , thread_ts=self.thread_ts['ts'] , ) time.sleep(1 ) def A__ ( ) -> Union[str, Any]: A : Any =os.environ['GITHUB_RUN_ID'] A : List[Any] =F'https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100' A : Union[str, Any] =requests.get(lowercase ).json() A : List[Any] ={} try: jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) A : List[str] =math.ceil((result['total_count'] - 100) / 100 ) for i in range(lowercase ): A : List[str] =requests.get(url + F'&page={i + 2}' ).json() jobs.update({job['name']: job['html_url'] for job in result['jobs']} ) return jobs except Exception as e: print('Unknown error, could not fetch links.', lowercase ) return {} def A__ ( lowercase: str ) -> Optional[Any]: A : Any ={} if os.path.exists(lowercase ): A : List[Any] =os.listdir(lowercase ) for file in files: try: with open(os.path.join(lowercase, lowercase ), encoding='utf-8' ) as f: A : Optional[int] =f.read() except UnicodeDecodeError as e: raise ValueError(F'Could not open {os.path.join(lowercase, lowercase )}.' ) from e return _artifact def A__ ( ) -> int: class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str ) -> List[str]: A : Dict =name A : Dict =[] def __str__( self : Optional[Any] ) -> List[str]: return self.name def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.paths.append({'name': self.name, 'path': path} ) A : Dict[str, Artifact] ={} A : str =filter(os.path.isdir, os.listdir() ) for directory in directories: A : Tuple =directory if artifact_name not in _available_artifacts: A : int =Artifact(lowercase ) _available_artifacts[artifact_name].add_path(lowercase ) return _available_artifacts if __name__ == "__main__": _lowercase : Optional[int] =get_job_links() _lowercase : str =retrieve_available_artifacts() _lowercase : List[Any] =collections.OrderedDict( [ ('''*.py''', '''API Examples'''), ('''*.md''', '''MD Examples'''), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' _lowercase : Optional[Any] ={ v: { '''failed''': [], '''failures''': {}, } for v in docs.values() } # Link to the GitHub Action job _lowercase : List[Any] =github_actions_job_links.get('''run_doctests''') _lowercase : int =available_artifacts['''doc_tests_gpu_test_reports'''].paths[0] _lowercase : Dict =retrieve_artifact(artifact_path['''name''']) if "stats" in artifact: _lowercase , _lowercase , _lowercase : List[Any] =handle_test_results(artifact['''stats''']) _lowercase : Any =failed _lowercase : Union[str, Any] =success _lowercase : str =time_spent[1:-1] + ''', ''' _lowercase : Any =extract_first_line_failure(artifact['''failures_short''']) for line in artifact["summary_short"].split('''\n'''): if re.search('''FAILED''', line): _lowercase : Tuple =line.replace('''FAILED ''', '''''') _lowercase : int =line.split()[0].replace('''\n''', '''''') if "::" in line: _lowercase , _lowercase : str =line.split('''::''') else: _lowercase , _lowercase : Union[str, Any] =line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): _lowercase : Any =docs[file_regex] doc_test_results[category]["failed"].append(test) _lowercase : Any =all_failures[test] if test in all_failures else '''N/A''' _lowercase : Tuple =failure break _lowercase : Optional[int] =Message('''๐Ÿค— Results of the doc tests.''', doc_test_results) message.post() message.post_reply()
661
1
def A__ ( lowercase: list, lowercase: int, lowercase: int = 0, lowercase: int = 0 ) -> int: A : Dict =right or len(lowercase ) - 1 if left > right: return -1 elif list_data[left] == key: return left elif list_data[right] == key: return right else: return search(lowercase, lowercase, left + 1, right - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
661
_lowercase : Dict ='''0.21.0''' from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
661
1
import os from collections.abc import Iterator def A__ ( lowercase: str = "." ) -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(lowercase ): A : Union[str, Any] =[d for d in dir_names if d != 'scripts' and d[0] not in '._'] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(lowercase )[1] in (".py", ".ipynb"): yield os.path.join(lowercase, lowercase ).lstrip('./' ) def A__ ( lowercase: Tuple ) -> Any: return F'{i * " "}*' if i else "\n##" def A__ ( lowercase: str, lowercase: str ) -> str: A : Union[str, Any] =old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(lowercase ) or old_parts[i] != new_part) and new_part: print(F'{md_prefix(lowercase )} {new_part.replace("_", " " ).title()}' ) return new_path def A__ ( lowercase: str = "." ) -> None: A : str ='' for filepath in sorted(good_file_paths(lowercase ) ): A , A : str =os.path.split(lowercase ) if filepath != old_path: A : Optional[int] =print_path(lowercase, lowercase ) A : Optional[Any] =(filepath.count(os.sep ) + 1) if filepath else 0 A : Any =F'{filepath}/{filename}'.replace(' ', '%20' ) A : Tuple =os.path.splitext(filename.replace('_', ' ' ).title() )[0] print(F'{md_prefix(lowercase )} [{filename}]({url})' ) if __name__ == "__main__": print_directory_md('''.''')
661
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
1
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
import math def A__ ( lowercase: int ) -> list: A : Optional[Any] =[True] * n A : Tuple =False A : List[Any] =False A : Dict =True for i in range(3, int(n**0.5 + 1 ), 2 ): A : Dict =i * 2 while index < n: A : Dict =False A : Dict =index + i A : Tuple =[2] for i in range(3, lowercase, 2 ): if is_prime[i]: primes.append(lowercase ) return primes def A__ ( lowercase: int = 999_966_663_333 ) -> int: A : Optional[int] =math.floor(math.sqrt(lowercase ) ) + 100 A : Optional[int] =prime_sieve(lowercase ) A : Optional[Any] =0 A : List[Any] =0 A : Union[str, Any] =primes[prime_index] while (last_prime**2) <= limit: A : Tuple =primes[prime_index + 1] A : Optional[int] =last_prime**2 A : Tuple =next_prime**2 # Get numbers divisible by lps(current) A : int =lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) A : List[Any] =upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps A : Any =0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair A : List[str] =next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
661
1
from typing import List from .keymap import KEYMAP, get_character def A__ ( lowercase: str ) -> List[str]: def decorator(lowercase: int ): A : Tuple =getattr(lowercase, 'handle_key', [] ) handle += [key] setattr(lowercase, 'handle_key', lowercase ) return func return decorator def A__ ( *lowercase: List[str] ) -> Dict: def decorator(lowercase: Union[str, Any] ): A : Optional[int] =getattr(lowercase, 'handle_key', [] ) handle += keys setattr(lowercase, 'handle_key', lowercase ) return func return decorator class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __new__( cls : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: A : Dict =super().__new__(cls , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not hasattr(SCREAMING_SNAKE_CASE__ , 'key_handler' ): setattr(SCREAMING_SNAKE_CASE__ , 'key_handler' , {} ) setattr(SCREAMING_SNAKE_CASE__ , 'handle_input' , KeyHandler.handle_input ) for value in attrs.values(): A : Optional[Any] =getattr(SCREAMING_SNAKE_CASE__ , 'handle_key' , [] ) for key in handled_keys: A : str =value return new_cls @staticmethod def SCREAMING_SNAKE_CASE_ ( cls : str ) -> Any: A : str =get_character() if char != KEYMAP["undefined"]: A : List[str] =ord(SCREAMING_SNAKE_CASE__ ) A : List[str] =cls.key_handler.get(SCREAMING_SNAKE_CASE__ ) if handler: A : List[str] =char return handler(cls ) else: return None def A__ ( cls: Optional[int] ) -> str: return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy() )
661
import heapq def A__ ( lowercase: dict ) -> set[int]: A : list[list] =[] # for each node and his adjacency list add them and the rank of the node to queue # using heapq module the queue will be filled like a Priority Queue # heapq works with a min priority queue, so I used -1*len(v) to build it for key, value in graph.items(): # O(log(n)) heapq.heappush(lowercase, [-1 * len(lowercase ), (key, value)] ) # chosen_vertices = set of chosen vertices A : Dict =set() # while queue isn't empty and there are still edges # (queue[0][0] is the rank of the node with max rank) while queue and queue[0][0] != 0: # extract vertex with max rank from queue and add it to chosen_vertices A : List[str] =heapq.heappop(lowercase )[1][0] chosen_vertices.add(lowercase ) # Remove all arcs adjacent to argmax for elem in queue: # if v haven't adjacent node, skip if elem[0] == 0: continue # if argmax is reachable from elem # remove argmax from elem's adjacent list and update his rank if argmax in elem[1][1]: A : str =elem[1][1].index(lowercase ) del elem[1][1][index] elem[0] += 1 # re-order the queue heapq.heapify(lowercase ) return chosen_vertices if __name__ == "__main__": import doctest doctest.testmod() _lowercase : List[Any] ={0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} print(f'''Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}''')
661
1
from statistics import mean, stdev def A__ ( lowercase: list, lowercase: int = 3 ) -> list: A : int =min(lowercase ) A : int =max(lowercase ) # normalize data return [round((x - x_min) / (x_max - x_min), lowercase ) for x in data] def A__ ( lowercase: list, lowercase: int = 3 ) -> list: A : Optional[int] =mean(lowercase ) A : Union[str, Any] =stdev(lowercase ) # standardize data return [round((x - mu) / (sigma), lowercase ) for x in data]
661
from typing import Dict, List, Optional, Union import numpy as np from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy _lowercase : List[Any] =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: A : Tuple =feature_size A : int =sampling_rate A : List[str] =padding_value A : Tuple =kwargs.pop('padding_side' , 'right' ) A : str =kwargs.pop('return_attention_mask' , SCREAMING_SNAKE_CASE__ ) super().__init__(**SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union[ BatchFeature, List[BatchFeature], Dict[str, BatchFeature], Dict[str, List[BatchFeature]], List[Dict[str, BatchFeature]], ] , SCREAMING_SNAKE_CASE__ : Union[bool, str, PaddingStrategy] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[Union[str, TensorType]] = None , ) -> BatchFeature: # If we have a list of dicts, let's convert it in a dict of lists # We do this to allow using this method as a collate_fn function in PyTorch Dataloader if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) and isinstance(processed_features[0] , (dict, BatchFeature) ): A : Tuple ={ key: [example[key] for example in processed_features] for key in processed_features[0].keys() } # The model's main input name, usually `input_values`, has be passed for padding if self.model_input_names[0] not in processed_features: raise ValueError( 'You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`' f' to this method that includes {self.model_input_names[0]}, but you provided' f' {list(processed_features.keys() )}' ) A : Dict =processed_features[self.model_input_names[0]] A : int =( return_attention_mask if return_attention_mask is not None else self.return_attention_mask ) if len(SCREAMING_SNAKE_CASE__ ) == 0: if return_attention_mask: A : List[Any] =[] return processed_features # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays # and rebuild them afterwards if no return_tensors is specified # Note that we lose the specific device the tensor may be on for PyTorch A : List[str] =required_input[0] if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ): # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element. A : Any =0 while len(required_input[index] ) == 0: index += 1 if index < len(SCREAMING_SNAKE_CASE__ ): A : Dict =required_input[index][0] if return_tensors is None: if is_tf_tensor(SCREAMING_SNAKE_CASE__ ): A : List[Any] ='tf' elif is_torch_tensor(SCREAMING_SNAKE_CASE__ ): A : Optional[int] ='pt' elif isinstance(SCREAMING_SNAKE_CASE__ , (int, float, list, tuple, np.ndarray) ): A : Union[str, Any] ='np' else: raise ValueError( f'type of {first_element} unknown: {type(SCREAMING_SNAKE_CASE__ )}. ' 'Should be one of a python, numpy, pytorch or tensorflow object.' ) for key, value in processed_features.items(): if isinstance(value[0] , (int, float) ): A : int =to_numpy(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =[to_numpy(SCREAMING_SNAKE_CASE__ ) for v in value] # Convert padding_strategy in PaddingStrategy A : List[Any] =self._get_padding_strategies(padding=SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ ) A : Optional[int] =processed_features[self.model_input_names[0]] A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if not all(len(SCREAMING_SNAKE_CASE__ ) == batch_size for v in processed_features.values() ): raise ValueError('Some items in the output dictionary have a different batch size than others.' ) A : Tuple =[] for i in range(SCREAMING_SNAKE_CASE__ ): A : int ={k: v[i] for k, v in processed_features.items()} # truncation A : List[Any] =self._truncate( SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , ) truncated_inputs.append(SCREAMING_SNAKE_CASE__ ) if padding_strategy == PaddingStrategy.LONGEST: # make sure that `max_length` cannot be longer than the longest truncated length A : Any =max(len(input_slice[self.model_input_names[0]] ) for input_slice in truncated_inputs ) A : Optional[Any] =PaddingStrategy.MAX_LENGTH A : List[Any] ={} for i in range(SCREAMING_SNAKE_CASE__ ): # padding A : Optional[Any] =self._pad( truncated_inputs[i] , max_length=SCREAMING_SNAKE_CASE__ , padding_strategy=SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) for key, value in outputs.items(): if key not in batch_outputs: A : Dict =[] if value.dtype is np.dtype(np.floataa ): A : Tuple =value.astype(np.floataa ) batch_outputs[key].append(SCREAMING_SNAKE_CASE__ ) return BatchFeature(SCREAMING_SNAKE_CASE__ , tensor_type=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> dict: A : Optional[int] =processed_features[self.model_input_names[0]] if padding_strategy == PaddingStrategy.LONGEST: A : List[str] =len(SCREAMING_SNAKE_CASE__ ) if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Tuple =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : int =padding_strategy != PaddingStrategy.DO_NOT_PAD and len(SCREAMING_SNAKE_CASE__ ) < max_length if return_attention_mask and "attention_mask" not in processed_features: A : str =np.ones(len(SCREAMING_SNAKE_CASE__ ) , dtype=np.intaa ) if needs_to_be_padded: A : Union[str, Any] =max_length - len(SCREAMING_SNAKE_CASE__ ) if self.padding_side == "right": if return_attention_mask: A : Dict =np.pad( processed_features['attention_mask'] , (0, difference) ) A : str =((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) elif self.padding_side == "left": if return_attention_mask: A : List[Any] =np.pad( processed_features['attention_mask'] , (difference, 0) ) A : Union[str, Any] =((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0) A : Tuple =np.pad( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'constant' , constant_values=self.padding_value ) else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return processed_features def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Union[Dict[str, np.ndarray], BatchFeature] , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Optional[Any]: if not truncation: return processed_features elif truncation and max_length is None: raise ValueError('When setting ``truncation=True``, make sure that ``max_length`` is defined.' ) A : Tuple =processed_features[self.model_input_names[0]] # find `max_length` that fits `pad_to_multiple_of` if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0): A : Any =((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of A : List[str] =len(SCREAMING_SNAKE_CASE__ ) > max_length if needs_to_be_truncated: A : Union[str, Any] =processed_features[self.model_input_names[0]][:max_length] if "attention_mask" in processed_features: A : Dict =processed_features['attention_mask'][:max_length] return processed_features def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=False , SCREAMING_SNAKE_CASE__ : Dict=None ) -> Union[str, Any]: # Get padding strategy if padding is not False: if padding is True: A : List[Any] =PaddingStrategy.LONGEST # Default to pad to the longest sequence in the batch elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Tuple =PaddingStrategy(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): A : Optional[int] =padding else: A : List[str] =PaddingStrategy.DO_NOT_PAD # Set max length if needed if max_length is None: if padding_strategy == PaddingStrategy.MAX_LENGTH: raise ValueError( f'When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined' ) # Test if we have a padding value if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None): raise ValueError( 'Asking to pad but the feature_extractor does not have a padding value. Please select a value to use' ' as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.' ) return padding_strategy
661
1
from __future__ import annotations _lowercase : str =1_0 def A__ ( lowercase: list[int] ) -> list[int]: A : Optional[Any] =1 A : Optional[int] =max(lowercase ) while placement <= max_digit: # declare and initialize empty buckets A : list[list] =[[] for _ in range(lowercase )] # split list_of_ints between the buckets for i in list_of_ints: A : Optional[Any] =int((i / placement) % RADIX ) buckets[tmp].append(lowercase ) # put each buckets' contents into list_of_ints A : str =0 for b in range(lowercase ): for i in buckets[b]: A : Union[str, Any] =i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
661
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging if TYPE_CHECKING: from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType _lowercase : Optional[int] =logging.get_logger(__name__) _lowercase : List[str] ={ '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''', '''microsoft/deberta-v2-xlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json''' ), '''microsoft/deberta-v2-xxlarge-mnli''': ( '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json''' ), } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : int = "deberta-v2" def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : str=12_81_00 , SCREAMING_SNAKE_CASE__ : List[Any]=15_36 , SCREAMING_SNAKE_CASE__ : Dict=24 , SCREAMING_SNAKE_CASE__ : List[str]=24 , SCREAMING_SNAKE_CASE__ : List[str]=61_44 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Any=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0_2 , SCREAMING_SNAKE_CASE__ : List[Any]=1e-7 , SCREAMING_SNAKE_CASE__ : Optional[int]=False , SCREAMING_SNAKE_CASE__ : Tuple=-1 , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : List[str]=0 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) A : Dict =hidden_size A : Optional[Any] =num_hidden_layers A : Optional[int] =num_attention_heads A : Optional[int] =intermediate_size A : Any =hidden_act A : Any =hidden_dropout_prob A : Union[str, Any] =attention_probs_dropout_prob A : Optional[Any] =max_position_embeddings A : Tuple =type_vocab_size A : Tuple =initializer_range A : int =relative_attention A : int =max_relative_positions A : Optional[Any] =pad_token_id A : Union[str, Any] =position_biased_input # Backwards compatibility if type(SCREAMING_SNAKE_CASE__ ) == str: A : Any =[x.strip() for x in pos_att_type.lower().split('|' )] A : Any =pos_att_type A : Tuple =vocab_size A : Any =layer_norm_eps A : Optional[Any] =kwargs.get('pooler_hidden_size' , SCREAMING_SNAKE_CASE__ ) A : str =pooler_dropout A : Any =pooler_hidden_act class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": A : List[Any] ={0: 'batch', 1: 'choice', 2: 'sequence'} else: A : int ={0: 'batch', 1: 'sequence'} if self._config.type_vocab_size > 0: return OrderedDict( [('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('token_type_ids', dynamic_axis)] ) else: return OrderedDict([('input_ids', dynamic_axis), ('attention_mask', dynamic_axis)] ) @property def SCREAMING_SNAKE_CASE_ ( self : int ) -> int: return 12 def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional["TensorType"] = None , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : int = 40 , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" = None , ) -> Mapping[str, Any]: A : str =super().generate_dummy_inputs(preprocessor=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs: del dummy_inputs["token_type_ids"] return dummy_inputs
661
1
from __future__ import annotations _lowercase : Optional[Any] ='''Muhammad Umer Farooq''' _lowercase : Dict ='''MIT''' _lowercase : Optional[int] ='''1.0.0''' _lowercase : Union[str, Any] ='''Muhammad Umer Farooq''' _lowercase : Optional[Any] ='''[email protected]''' _lowercase : Dict ='''Alpha''' import re from html.parser import HTMLParser from urllib import parse import requests class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : str ) -> None: super().__init__() A : list[str] =[] A : List[Any] =domain def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : list[tuple[str, str | None]] ) -> None: # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: A : int =parse.urljoin(self.domain , SCREAMING_SNAKE_CASE__ ) self.urls.append(SCREAMING_SNAKE_CASE__ ) def A__ ( lowercase: str ) -> str: return ".".join(get_sub_domain_name(lowercase ).split('.' )[-2:] ) def A__ ( lowercase: str ) -> str: return parse.urlparse(lowercase ).netloc def A__ ( lowercase: str = "https://github.com" ) -> list[str]: A : List[str] =get_domain_name(lowercase ) # Initialize the parser A : str =Parser(lowercase ) try: # Open URL A : Tuple =requests.get(lowercase ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through A : List[Any] =set() for link in parser.urls: # open URL. # read = requests.get(link) try: A : int =requests.get(lowercase ) # Get the valid email. A : str =re.findall('[a-zA-Z0-9]+@' + domain, read.text ) # If not in list then append it. for email in emails: valid_emails.add(lowercase ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(lowercase ) if __name__ == "__main__": _lowercase : Any =emails_from_url('''https://github.com''') print(f'''{len(emails)} emails found:''') print('''\n'''.join(sorted(emails)))
661
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
1
from abc import ABC, abstractmethod from typing import List, Optional class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple ) -> Any: # test for the above condition self.test() def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[str]: A : Tuple =0 A : List[str] =False while not completed: if counter == 1: self.reset() A : Any =self.advance() if not self.does_advance(SCREAMING_SNAKE_CASE__ ): raise Exception( 'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.' ) A , A , A : Union[str, Any] =self.update(SCREAMING_SNAKE_CASE__ ) counter += 1 if counter > 1_00_00: raise Exception('update() does not fulfill the constraint.' ) if self.remaining() != 0: raise Exception('Custom Constraint is not defined correctly.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Any: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Dict: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Tuple: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) @abstractmethod def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=False ) -> str: raise NotImplementedError( f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.' ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : List[int] ) -> Dict: super(SCREAMING_SNAKE_CASE__ , self ).__init__() if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0: raise ValueError(f'`token_ids` has to be a non-empty list, but is {token_ids}.' ) if any((not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or token_id < 0) for token_id in token_ids ): raise ValueError(f'Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.' ) A : Dict =token_ids A : List[str] =len(self.token_ids ) A : List[Any] =-1 # the index of the currently fulfilled step A : List[Any] =False def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def SCREAMING_SNAKE_CASE_ ( self : Dict , SCREAMING_SNAKE_CASE__ : int ) -> List[str]: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'`token_id` has to be an `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}' ) A : Tuple =False A : int =False A : int =False if self.does_advance(SCREAMING_SNAKE_CASE__ ): self.fulfilled_idx += 1 A : Optional[int] =True if self.fulfilled_idx == (self.seqlen - 1): A : Optional[Any] =True A : List[str] =completed else: # failed to make progress. A : Dict =True self.reset() return stepped, completed, reset def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: A : List[Any] =False A : List[str] =0 def SCREAMING_SNAKE_CASE_ ( self : int ) -> Tuple: return self.seqlen - (self.fulfilled_idx + 1) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=False ) -> int: A : List[str] =PhrasalConstraint(self.token_ids ) if stateful: A : str =self.seqlen A : Dict =self.fulfilled_idx A : Any =self.completed return new_constraint class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[List[int]] , SCREAMING_SNAKE_CASE__ : int=True ) -> int: A : Any =max([len(SCREAMING_SNAKE_CASE__ ) for one in nested_token_ids] ) A : Tuple ={} for token_ids in nested_token_ids: A : List[Any] =root for tidx, token_id in enumerate(SCREAMING_SNAKE_CASE__ ): if token_id not in level: A : int ={} A : str =level[token_id] if no_subsets and self.has_subsets(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError( 'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is' f' {nested_token_ids}.' ) A : str =root def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: A : Tuple =self.trie for current_token in current_seq: A : List[Any] =start[current_token] A : str =list(start.keys() ) return next_tokens def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: A : List[str] =self.next_tokens(SCREAMING_SNAKE_CASE__ ) return len(SCREAMING_SNAKE_CASE__ ) == 0 def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Union[str, Any]: A : List[Any] =list(root.values() ) if len(SCREAMING_SNAKE_CASE__ ) == 0: return 1 else: return sum([self.count_leaves(SCREAMING_SNAKE_CASE__ ) for nn in next_nodes] ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: A : List[str] =self.count_leaves(SCREAMING_SNAKE_CASE__ ) return len(SCREAMING_SNAKE_CASE__ ) != leaf_count class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Dict , SCREAMING_SNAKE_CASE__ : List[List[int]] ) -> Tuple: super(SCREAMING_SNAKE_CASE__ , self ).__init__() if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or len(SCREAMING_SNAKE_CASE__ ) == 0: raise ValueError(f'`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.' ) if any(not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for token_ids in nested_token_ids ): raise ValueError(f'`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.' ) if any( any((not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f'Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.' ) A : Dict =DisjunctiveTrie(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =nested_token_ids A : List[str] =self.trie.max_height A : str =[] A : Optional[Any] =False def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: A : Dict =self.trie.next_tokens(self.current_seq ) if len(SCREAMING_SNAKE_CASE__ ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> Tuple: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}' ) A : Tuple =self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'`token_id` is supposed to be type `int`, but is {token_id} of type {type(SCREAMING_SNAKE_CASE__ )}' ) A : int =False A : Dict =False A : Tuple =False if self.does_advance(SCREAMING_SNAKE_CASE__ ): self.current_seq.append(SCREAMING_SNAKE_CASE__ ) A : str =True else: A : Tuple =True self.reset() A : Union[str, Any] =self.trie.reached_leaf(self.current_seq ) A : Any =completed return stepped, completed, reset def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Tuple: A : Tuple =False A : List[Any] =[] def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int=False ) -> int: A : List[Any] =DisjunctiveConstraint(self.token_ids ) if stateful: A : Optional[int] =self.seqlen A : List[str] =self.current_seq A : List[Any] =self.completed return new_constraint class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[Constraint] ) -> Any: A : Any =constraints # max # of steps required to fulfill a given constraint A : Any =max([c.seqlen for c in constraints] ) A : List[str] =len(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =False self.init_state() def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Union[str, Any]: A : Union[str, Any] =[] A : Dict =None A : List[Any] =[constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) for constraint in self.constraints] def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[Any]: A : int =0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Optional[int]: A : Optional[Any] =[] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" A : Any =constraint.advance() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): token_list.append(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): token_list.extend(SCREAMING_SNAKE_CASE__ ) else: A : List[Any] =self.inprogress_constraint.advance() if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): token_list.append(SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): token_list.extend(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) == 0: return None else: return token_list def SCREAMING_SNAKE_CASE_ ( self : str , SCREAMING_SNAKE_CASE__ : Optional[List[int]] ) -> Tuple: self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint A , A : Optional[Any] =self.add(SCREAMING_SNAKE_CASE__ ) # the entire list of constraints are fulfilled if self.completed: break def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> List[Any]: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError(f'`token_id` should be an `int`, but is `{token_id}`.' ) A , A : str =False, False if self.completed: A : int =True A : List[str] =False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state A , A , A : List[Any] =self.inprogress_constraint.update(SCREAMING_SNAKE_CASE__ ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) ) A : Union[str, Any] =None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) A : Optional[int] =None if len(self.pending_constraints ) == 0: # we're done! A : Union[str, Any] =True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(SCREAMING_SNAKE_CASE__ ): A , A , A : str =pending_constraint.update(SCREAMING_SNAKE_CASE__ ) if not stepped: raise Exception( '`constraint.update(token_id)` is not yielding incremental progress, ' 'even though `constraint.does_advance(token_id)` is true.' ) if complete: self.complete_constraints.append(SCREAMING_SNAKE_CASE__ ) A : Tuple =None if not complete and stepped: A : Optional[Any] =pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". A : Tuple =( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. A : Optional[int] =True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Optional[int]=True ) -> Any: A : Dict =ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: A : Any =[ constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: A : List[str] =self.inprogress_constraint.copy(stateful=SCREAMING_SNAKE_CASE__ ) A : Tuple =[constraint.copy() for constraint in self.pending_constraints] return new_state
661
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Optional[int] =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[str] = XLMRobertaTokenizer lowercase : Dict = XLMRobertaTokenizerFast lowercase : str = True lowercase : Tuple = True def SCREAMING_SNAKE_CASE_ ( self : int ) -> Optional[Any]: super().setUp() # We have a SentencePiece fixture for testing A : List[str] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[Any]: A : List[str] ='<pad>' A : int =1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: A : List[str] =list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 10_02 ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Union[str, Any] =XLMRobertaTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.tokenize('This is a test' ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ['โ–This', 'โ–is', 'โ–a', 'โ–t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) A : Any =tokenizer.tokenize('I was born in 92000, and this is falsรฉ.' ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'รฉ', '.', ] , ) A : Tuple =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) A : Union[str, Any] =tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Optional[int]: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return A : Any =(self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ): A : List[Any] =self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : Dict =self.tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) A : str =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) A : List[str] =tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Dict =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=True A : Optional[int] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it save with the same files self.assertSequenceEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Checks everything loads correctly in the same way A : Tuple =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) # Save tokenizer rust, legacy_format=False A : List[Any] =tempfile.mkdtemp() A : Optional[int] =tokenizer_r.save_pretrained(SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer_p.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way A : List[Any] =tokenizer_r.from_pretrained(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer_p.from_pretrained(SCREAMING_SNAKE_CASE__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) @cached_property def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[int]: return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Any: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(SCREAMING_SNAKE_CASE__ , f.name ) A : Optional[Any] =XLMRobertaTokenizer(f.name , keep_accents=SCREAMING_SNAKE_CASE__ ) A : int =pickle.dumps(SCREAMING_SNAKE_CASE__ ) pickle.loads(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Union[str, Any]: if not self.test_rust_tokenizer: return A : Union[str, Any] =self.get_tokenizer() A : int =self.get_rust_tokenizer() A : List[str] ='I was born in 92000, and this is falsรฉ.' A : Union[str, Any] =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Tuple =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.get_rust_tokenizer() A : int =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : Dict =rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[str]: A : Any ='Hello World!' A : Optional[Any] =[0, 3_53_78, 66_61, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> str: A : Any =( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) A : int =[ 0, 32_93, 83, 10, 45_52, 49_89, 79_86, 6_78, 10, 59_15, 1_11, 17_94_59, 12_48_50, 4, 60_44, 2_37, 12, 6, 5, 6, 4, 67_80, 7_05, 15, 13_88, 44, 3_78, 1_01_14, 7_11, 1_52, 20, 6, 5, 2_23_76, 6_42, 12_21, 1_51_90, 3_41_53, 4_50, 56_08, 9_59, 11_19, 5_77_02, 1_36, 1_86, 47, 10_98, 2_93_67, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 60_44, 2_37, 62_84, 5_09_01, 5_28, 31, 90, 34, 9_27, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Any: # fmt: off A : List[Any] ={'input_ids': [[0, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [0, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 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], [0, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 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]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
661
1
from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' lowercase : Tuple = [r"h\.\d+\.attn\.bias", r"h\.\d+\.attn\.masked_bias"] @register_to_config def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : int = 5_02_57 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : str = "gelu_new" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 1e-5 , SCREAMING_SNAKE_CASE__ : float = 0.0_2 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> List[str]: super().__init__() A : str =prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( f'`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and' f' `n_embd`: {n_embd} are not equal.' ) A : List[Any] =prefix_inner_dim A : Dict =prefix_hidden_dim A : List[str] =( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Optional[int] =( nn.Linear(self.prefix_hidden_dim , SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None else nn.Identity() ) A : Dict =GPTaConfig( vocab_size=SCREAMING_SNAKE_CASE__ , n_positions=SCREAMING_SNAKE_CASE__ , n_embd=SCREAMING_SNAKE_CASE__ , n_layer=SCREAMING_SNAKE_CASE__ , n_head=SCREAMING_SNAKE_CASE__ , n_inner=SCREAMING_SNAKE_CASE__ , activation_function=SCREAMING_SNAKE_CASE__ , resid_pdrop=SCREAMING_SNAKE_CASE__ , embd_pdrop=SCREAMING_SNAKE_CASE__ , attn_pdrop=SCREAMING_SNAKE_CASE__ , layer_norm_epsilon=SCREAMING_SNAKE_CASE__ , initializer_range=SCREAMING_SNAKE_CASE__ , scale_attn_weights=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ , scale_attn_by_inverse_layer_idx=SCREAMING_SNAKE_CASE__ , reorder_and_upcast_attn=SCREAMING_SNAKE_CASE__ , ) A : Dict =GPTaLMHeadModel(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : torch.Tensor , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , ) -> Optional[Any]: A : str =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) A : Any =self.encode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =self.decode_prefix(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: A : int =self.get_dummy_token(input_ids.shape[0] , input_ids.device ) A : Optional[int] =torch.cat((dummy_token, input_ids) , dim=1 ) A : Dict =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.device ) -> torch.Tensor: return torch.zeros(SCREAMING_SNAKE_CASE__ , self.prefix_length , dtype=torch.intaa , device=SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: return self.encode_prefix(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> Dict: A : Dict =torch.split(SCREAMING_SNAKE_CASE__ , 1 , dim=0 ) A : int =[] A : Optional[int] =[] for feature in features: A : int =self.decode_prefix(feature.to(SCREAMING_SNAKE_CASE__ ) ) # back to the clip feature # Only support beam search for now A , A : Dict =self.generate_beam( input_embeds=SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) A : str =torch.stack(SCREAMING_SNAKE_CASE__ ) A : int =torch.stack(SCREAMING_SNAKE_CASE__ ) return generated_tokens, generated_seq_lengths @torch.no_grad() def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Tuple=None , SCREAMING_SNAKE_CASE__ : int = 5 , SCREAMING_SNAKE_CASE__ : int = 67 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : Optional[int] = None , ) -> Dict: A : Dict =eos_token_id A : str =None A : List[Any] =None A : List[Any] =torch.ones(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.int ) A : str =torch.zeros(SCREAMING_SNAKE_CASE__ , device=SCREAMING_SNAKE_CASE__ , dtype=torch.bool ) if input_embeds is not None: A : Any =input_embeds else: A : List[Any] =self.transformer.transformer.wte(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): A : Any =self.transformer(inputs_embeds=SCREAMING_SNAKE_CASE__ ) A : str =outputs.logits A : Union[str, Any] =logits[:, -1, :] / (temperature if temperature > 0 else 1.0) A : List[str] =logits.softmax(-1 ).log() if scores is None: A , A : Any =logits.topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Any =generated.expand(SCREAMING_SNAKE_CASE__ , *generated.shape[1:] ) A , A : Tuple =next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: A : Union[str, Any] =next_tokens else: A : str =tokens.expand(SCREAMING_SNAKE_CASE__ , *tokens.shape[1:] ) A : Optional[int] =torch.cat((tokens, next_tokens) , dim=1 ) else: A : Optional[Any] =-float(np.inf ) A : Tuple =0 A : Optional[Any] =scores[:, None] + logits seq_lengths[~is_stopped] += 1 A : int =scores_sum / seq_lengths[:, None] A , A : Optional[int] =scores_sum_average.view(-1 ).topk(SCREAMING_SNAKE_CASE__ , -1 ) A : Dict =next_tokens // scores_sum.shape[1] A : Optional[Any] =seq_lengths[next_tokens_source] A : Tuple =next_tokens % scores_sum.shape[1] A : Optional[Any] =next_tokens.unsqueeze(1 ) A : Optional[Any] =tokens[next_tokens_source] A : Any =torch.cat((tokens, next_tokens) , dim=1 ) A : List[str] =generated[next_tokens_source] A : List[Any] =scores_sum_average * seq_lengths A : Optional[Any] =is_stopped[next_tokens_source] A : Optional[int] =self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) A : Any =torch.cat((generated, next_token_embed) , dim=1 ) A : Optional[int] =is_stopped + next_tokens.eq(SCREAMING_SNAKE_CASE__ ).squeeze() if is_stopped.all(): break A : Optional[Any] =scores / seq_lengths A : str =scores.argsort(descending=SCREAMING_SNAKE_CASE__ ) # tokens tensors are already padded to max_seq_length A : Optional[Any] =[tokens[i] for i in order] A : Any =torch.stack(SCREAMING_SNAKE_CASE__ , dim=0 ) A : str =torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
661
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : int =logging.get_logger(__name__) _lowercase : Dict ={ '''facebook/xglm-564M''': '''https://huggingface.co/facebook/xglm-564M/resolve/main/config.json''', # See all XGLM models at https://huggingface.co/models?filter=xglm } class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[int] = "xglm" lowercase : Any = ["past_key_values"] lowercase : Dict = { "num_attention_heads": "attention_heads", "hidden_size": "d_model", "num_hidden_layers": "num_layers", } def __init__( self : int , SCREAMING_SNAKE_CASE__ : List[Any]=25_60_08 , SCREAMING_SNAKE_CASE__ : Dict=20_48 , SCREAMING_SNAKE_CASE__ : List[Any]=10_24 , SCREAMING_SNAKE_CASE__ : str=40_96 , SCREAMING_SNAKE_CASE__ : Optional[int]=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Any="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[Any]=0.0_2 , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : List[Any]=1 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : List[str]=2 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: A : str =vocab_size A : Union[str, Any] =max_position_embeddings A : Optional[Any] =d_model A : Optional[int] =ffn_dim A : int =num_layers A : Any =attention_heads A : Dict =activation_function A : List[Any] =dropout A : str =attention_dropout A : List[Any] =activation_dropout A : List[Any] =layerdrop A : List[Any] =init_std A : Union[str, Any] =scale_embedding # scale factor will be sqrt(d_model) if True A : List[str] =use_cache super().__init__( pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , decoder_start_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
661
1
def A__ ( lowercase: int ) -> int: assert isinstance(lowercase, lowercase ), F'The input value of [n={number}] is not an integer' if number == 1: return 2 elif number < 1: A : Any =F'The input value of [n={number}] has to be > 0' raise ValueError(lowercase ) else: A : Any =sylvester(number - 1 ) A : List[Any] =num - 1 A : Union[str, Any] =num return lower * upper + 1 if __name__ == "__main__": print(f'''The 8th number in Sylvester\'s sequence: {sylvester(8)}''')
661
# Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input _lowercase : List[str] ='''Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine''' def A__ ( ) -> List[Any]: A : Any =_ask_options( 'In which compute environment are you running?', ['This machine', 'AWS (Amazon SageMaker)'], _convert_compute_environment, ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: A : Tuple =get_sagemaker_input() else: A : str =get_cluster_input() return config def A__ ( lowercase: int=None ) -> str: if subparsers is not None: A : List[str] =subparsers.add_parser('config', description=lowercase ) else: A : Union[str, Any] =argparse.ArgumentParser('Accelerate config command', description=lowercase ) parser.add_argument( '--config_file', default=lowercase, help=( 'The path to use to store the config file. Will default to a file named default_config.yaml in the cache ' 'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have ' 'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed ' 'with \'huggingface\'.' ), ) if subparsers is not None: parser.set_defaults(func=lowercase ) return parser def A__ ( lowercase: Tuple ) -> List[Any]: A : Union[str, Any] =get_user_input() if args.config_file is not None: A : Optional[Any] =args.config_file else: if not os.path.isdir(lowercase ): os.makedirs(lowercase ) A : Union[str, Any] =default_yaml_config_file if config_file.endswith('.json' ): config.to_json_file(lowercase ) else: config.to_yaml_file(lowercase ) print(F'accelerate configuration saved at {config_file}' ) def A__ ( ) -> Optional[int]: A : Any =config_command_parser() A : int =parser.parse_args() config_command(lowercase ) if __name__ == "__main__": main()
661
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 _lowercase : Any =1_6 _lowercase : int =3_2 def A__ ( lowercase: Union[str, Any] ) -> List[Any]: return int(x / 2**20 ) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __enter__( self : Tuple ) -> Tuple: gc.collect() torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero A : Optional[int] =torch.cuda.memory_allocated() return self def __exit__( self : Optional[int] , *SCREAMING_SNAKE_CASE__ : int ) -> Tuple: gc.collect() torch.cuda.empty_cache() A : Dict =torch.cuda.memory_allocated() A : Any =torch.cuda.max_memory_allocated() A : List[str] =bamb(self.end - self.begin ) A : Optional[Any] =bamb(self.peak - self.begin ) # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased", lowercase: int = 320, lowercase: int = 160, ) -> int: A : Any =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset( 'glue', 'mrpc', split={'train': F'train[:{n_train}]', 'validation': F'validation[:{n_val}]'} ) def tokenize_function(lowercase: str ): # max_length=None => use the model max length (it's actually the default) A : List[Any] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Dict =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Optional[Any] =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: List[str] ): # 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Optional[int] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : Optional[Any] =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Tuple, lowercase: Optional[Any] ) -> List[str]: # Initialize accelerator A : Optional[Any] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : Optional[Any] =config['lr'] A : Union[str, Any] =int(config['num_epochs'] ) A : Dict =int(config['seed'] ) A : Optional[Any] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : List[Any] =get_dataloaders(lowercase, lowercase, lowercase, args.n_train, args.n_val ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : Optional[int] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : Any =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : List[Any] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Tuple =1 A : str =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : str =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : Optional[int] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : str =0 # We also need to keep track of the stating epoch so files are named properly A : Optional[Any] =0 # Now we train the model A : Tuple ={} for epoch in range(lowercase, lowercase ): with TorchTracemalloc() as tracemalloc: model.train() for step, batch in enumerate(lowercase ): A : Dict =model(**lowercase ) A : Optional[Any] =outputs.loss A : str =loss / gradient_accumulation_steps accelerator.backward(lowercase ) 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 ) ) ) A : List[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(lowercase, lowercase ) def A__ ( ) -> List[str]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, 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=lowercase, default=lowercase, 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=lowercase, default=320, help='Number of training examples to use.', ) parser.add_argument( '--n_val', type=lowercase, default=160, help='Number of validation examples to use.', ) parser.add_argument( '--num_epochs', type=lowercase, default=1, help='Number of train epochs.', ) A : List[Any] =parser.parse_args() A : Any ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
import collections import importlib.util import os import re from pathlib import Path _lowercase : List[str] ='''src/transformers''' # Matches is_xxx_available() _lowercase : Dict =re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} _lowercase : List[Any] =re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _lowercase : Tuple =re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available _lowercase : Dict =re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") _lowercase : List[Any] =re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _lowercase : str =re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", _lowercase : Optional[int] =re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], _lowercase : Any =re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo _lowercase : List[Any] =re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: _lowercase : Optional[Any] =re.compile(R'''^\s*try:''') # Catches a line with else: _lowercase : List[Any] =re.compile(R'''^\s*else:''') def A__ ( lowercase: Dict ) -> int: if _re_test_backend.search(lowercase ) is None: return None A : Any =[b[0] for b in _re_backend.findall(lowercase )] backends.sort() return "_and_".join(lowercase ) def A__ ( lowercase: Any ) -> List[Any]: with open(lowercase, 'r', encoding='utf-8', newline='\n' ) as f: A : Optional[Any] =f.readlines() A : Dict =0 while line_index < len(lowercase ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lowercase ): return None # First grab the objects without a specific backend in _import_structure A : Optional[int] =[] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: A : int =lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(lowercase ): A : int =_re_one_line_import_struct.search(lowercase ).groups()[0] A : int =re.findall('\[([^\]]+)\]', lowercase ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue A : Optional[int] =_re_import_struct_key_value.search(lowercase ) if single_line_import_search is not None: A : Dict =[obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(lowercase ) > 0] objects.extend(lowercase ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 A : str ={'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. A : Optional[int] =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: A : str =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): A : Optional[Any] =lines[line_index] if _re_import_struct_add_one.search(lowercase ) is not None: objects.append(_re_import_struct_add_one.search(lowercase ).groups()[0] ) elif _re_import_struct_add_many.search(lowercase ) is not None: A : Optional[Any] =_re_import_struct_add_many.search(lowercase ).groups()[0].split(', ' ) A : int =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_between_brackets.search(lowercase ) is not None: A : Optional[int] =_re_between_brackets.search(lowercase ).groups()[0].split(', ' ) A : Optional[int] =[obj[1:-1] for obj in imports if len(lowercase ) > 0] objects.extend(lowercase ) elif _re_quote_object.search(lowercase ) is not None: objects.append(_re_quote_object.search(lowercase ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 A : Optional[Any] =objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend A : Optional[Any] =[] while ( line_index < len(lowercase ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): A : Any =lines[line_index] A : Optional[int] =_re_import.search(lowercase ) 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 A : Optional[Any] ={'none': objects} # Let's continue with backend-specific objects while line_index < len(lowercase ): # If the line is an if is_backend_available, we grab all objects associated. A : str =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: A : Optional[Any] =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 A : List[str] =[] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): A : Any =lines[line_index] A : Any =_re_import.search(lowercase ) 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 A : Dict =objects else: line_index += 1 return import_dict_objects, type_hint_objects def A__ ( lowercase: Any, lowercase: int ) -> Dict: def find_duplicates(lowercase: List[str] ): return [k for k, v in collections.Counter(lowercase ).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!"] A : List[Any] =[] for key in import_dict_objects.keys(): A : List[Any] =find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'Duplicate _import_structure definitions for: {duplicate_imports}' ) A : Tuple =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] ) ): A : Tuple ='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 A__ ( ) -> List[str]: A : Dict =[] for root, _, files in os.walk(lowercase ): if "__init__.py" in files: A : Any =os.path.join(lowercase, '__init__.py' ) A : Union[str, Any] =parse_init(lowercase ) if objects is not None: A : str =analyze_results(*lowercase ) if len(lowercase ) > 0: A : Any =F'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(lowercase ) ) if len(lowercase ) > 0: raise ValueError('\n\n'.join(lowercase ) ) def A__ ( ) -> int: A : List[str] =[] for path, directories, files in os.walk(lowercase ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(lowercase ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(lowercase ) / folder).glob('*.py' ) ) ) == 0: continue A : Any =str((Path(lowercase ) / folder).relative_to(lowercase ) ) A : List[str] =short_path.replace(os.path.sep, '.' ) submodules.append(lowercase ) for fname in files: if fname == "__init__.py": continue A : Optional[Any] =str((Path(lowercase ) / fname).relative_to(lowercase ) ) A : Dict =short_path.replace('.py', '' ).replace(os.path.sep, '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(lowercase ) return submodules _lowercase : Tuple =[ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def A__ ( ) -> Tuple: # This is to make sure the transformers module imported is the one in the repo. A : str =importlib.util.spec_from_file_location( 'transformers', os.path.join(lowercase, '__init__.py' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) A : Any =spec.loader.load_module() A : Any =[ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(lowercase ) > 0: A : Dict ='\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()
661
1
import uuid from typing import Any, Dict, List, Optional, Union from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, Pipeline if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch _lowercase : Dict =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : uuid.UUID = None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Optional[int]: if not conversation_id: A : Any =uuid.uuida() if past_user_inputs is None: A : List[Any] =[] if generated_responses is None: A : int =[] A : uuid.UUID =conversation_id A : List[str] =past_user_inputs A : List[str] =generated_responses A : Optional[str] =text def __eq__( self : str , SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return False if self.uuid == other.uuid: return True return ( self.new_user_input == other.new_user_input and self.past_user_inputs == other.past_user_inputs and self.generated_responses == other.generated_responses ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : bool = False ) -> Optional[int]: if self.new_user_input: if overwrite: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten ' f'with: "{text}".' ) A : Optional[Any] =text else: logger.warning( f'User input added while unprocessed input was existing: "{self.new_user_input}" new input ' f'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input' ) else: A : Optional[Any] =text def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: if self.new_user_input: self.past_user_inputs.append(self.new_user_input ) A : int =None def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> Dict: self.generated_responses.append(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: for user_input, generated_response in zip(self.past_user_inputs , self.generated_responses ): yield True, user_input yield False, generated_response if self.new_user_input: yield True, self.new_user_input def __repr__( self : Any ) -> List[str]: A : str =f'Conversation id: {self.uuid} \n' for is_user, text in self.iter_texts(): A : Optional[int] ='user' if is_user else 'bot' output += f'{name} >> {text} \n' return output @add_end_docstrings( lowerCAmelCase_ , r"\n min_length_for_response (`int`, *optional*, defaults to 32):\n The minimum length (in number of tokens) for a response.\n minimum_tokens (`int`, *optional*, defaults to 10):\n The minimum length of tokens to leave for a response.\n " , ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : str , *SCREAMING_SNAKE_CASE__ : Tuple , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if self.tokenizer.pad_token_id is None: A : Optional[Any] =self.tokenizer.eos_token def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , **SCREAMING_SNAKE_CASE__ : List[str] ) -> str: A : Optional[int] ={} A : Any ={} A : List[str] ={} if min_length_for_response is not None: A : List[Any] =min_length_for_response if minimum_tokens is not None: A : Dict =minimum_tokens if "max_length" in generate_kwargs: A : int =generate_kwargs['max_length'] # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length) if clean_up_tokenization_spaces is not None: A : List[Any] =clean_up_tokenization_spaces if generate_kwargs: forward_params.update(SCREAMING_SNAKE_CASE__ ) return preprocess_params, forward_params, postprocess_params def __call__( self : int , SCREAMING_SNAKE_CASE__ : Union[Conversation, List[Conversation]] , SCREAMING_SNAKE_CASE__ : Dict=0 , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: A : Dict =super().__call__(SCREAMING_SNAKE_CASE__ , num_workers=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) == 1: return outputs[0] return outputs def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Conversation , SCREAMING_SNAKE_CASE__ : str=32 ) -> Dict[str, Any]: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): raise ValueError('ConversationalPipeline, expects Conversation as inputs' ) if conversation.new_user_input is None: raise ValueError( f'Conversation with UUID {type(conversation.uuid )} does not contain new user input to process. ' 'Add user inputs with the conversation\'s `add_user_input` method' ) if hasattr(self.tokenizer , '_build_conversation_input_ids' ): A : int =self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE__ ) else: # If the tokenizer cannot handle conversations, we default to only the old version A : Union[str, Any] =self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE__ ) if self.framework == "pt": A : Any =torch.LongTensor([input_ids] ) elif self.framework == "tf": A : Union[str, Any] =tf.constant([input_ids] ) return {"input_ids": input_ids, "conversation": conversation} def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 , **SCREAMING_SNAKE_CASE__ : int ) -> Optional[Any]: A : int =generate_kwargs.get('max_length' , self.model.config.max_length ) A : Dict =model_inputs['input_ids'].shape[1] if max_length - minimum_tokens < n: logger.warning(f'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})' ) A : Any =max_length - minimum_tokens A : str =model_inputs['input_ids'][:, -trim:] if "attention_mask" in model_inputs: A : List[Any] =model_inputs['attention_mask'][:, -trim:] A : int =model_inputs.pop('conversation' ) A : List[Any] =max_length A : Optional[Any] =self.model.generate(**SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if self.model.config.is_encoder_decoder: A : str =1 else: A : List[Any] =n return {"output_ids": output_ids[:, start_position:], "conversation": conversation} def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any=True ) -> Tuple: A : Optional[Any] =model_outputs['output_ids'] A : Optional[int] =self.tokenizer.decode( output_ids[0] , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ , ) A : Any =model_outputs['conversation'] conversation.mark_processed() conversation.append_response(SCREAMING_SNAKE_CASE__ ) return conversation def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : Conversation ) -> Dict: A : Any =self.tokenizer.eos_token_id A : Optional[int] =[] for is_user, text in conversation.iter_texts(): if eos_token_id is not None: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) + [eos_token_id] ) else: input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) > self.tokenizer.model_max_length: A : Tuple =input_ids[-self.tokenizer.model_max_length :] return input_ids
661
import logging from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import arg_to_scheduler from transformers import TrainingArguments _lowercase : Any =logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' lowercase : Optional[float] = field( default=0.0 , metadata={"help": "The label smoothing epsilon to apply (if not zero)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "Whether to SortishSamler or not."} ) lowercase : bool = field( default=lowerCAmelCase_ , metadata={"help": "Whether to use generate to calculate generative metrics (ROUGE, BLEU)."} ) lowercase : bool = field(default=lowerCAmelCase_ , metadata={"help": "whether to use adafactor"} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Encoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Decoder layer dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field(default=lowerCAmelCase_ , metadata={"help": "Dropout probability. Goes into model.config."} ) lowercase : Optional[float] = field( default=lowerCAmelCase_ , metadata={"help": "Attention dropout probability. Goes into model.config."} ) lowercase : Optional[str] = field( default="linear" , metadata={"help": f'Which lr scheduler to use. Selected in {sorted(arg_to_scheduler.keys() )}'} , )
661
1
import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor _lowercase : Any =logging.get_logger(__name__) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : int , *SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Tuple ) -> None: warnings.warn( 'The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use FlavaImageProcessor instead.' , SCREAMING_SNAKE_CASE__ , ) super().__init__(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
661
import argparse import json import os import re import shutil import torch from transformers import BioGptConfig, BioGptForCausalLM from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE from transformers.utils import WEIGHTS_NAME, logging logging.set_verbosity_warning() _lowercase : int =2 class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def __init__( self : List[Any] , *, # begin keyword-only arguments SCREAMING_SNAKE_CASE__ : List[Any]="<s>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : List[str]="</s>" , SCREAMING_SNAKE_CASE__ : Optional[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : int=None , ) -> List[Any]: A , A , A , A : Optional[Any] =bos, unk, pad, eos A : Dict =[] A : Union[str, Any] =[] A : Any ={} A : int =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : Any =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[Any] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =self.add_symbol(SCREAMING_SNAKE_CASE__ ) if extra_special_symbols: for s in extra_special_symbols: self.add_symbol(SCREAMING_SNAKE_CASE__ ) A : List[str] =len(self.symbols ) def __eq__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: return self.indices == other.indices def __getitem__( self : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if idx < len(self.symbols ): return self.symbols[idx] return self.unk_word def __len__( self : List[Any] ) -> Union[str, Any]: return len(self.symbols ) def __contains__( self : Dict , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: return sym in self.indices @classmethod def SCREAMING_SNAKE_CASE_ ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : int ) -> Any: A : Union[str, Any] =cls() d.add_from_file(SCREAMING_SNAKE_CASE__ ) return d def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Any=1 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False ) -> Any: if word in self.indices and not overwrite: A : int =self.indices[word] A : Union[str, Any] =self.count[idx] + n return idx else: A : Tuple =len(self.symbols ) A : str =idx self.symbols.append(SCREAMING_SNAKE_CASE__ ) self.count.append(SCREAMING_SNAKE_CASE__ ) return idx def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: return 0 def SCREAMING_SNAKE_CASE_ ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): try: with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' ) as fd: self.add_from_file(SCREAMING_SNAKE_CASE__ ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception('Incorrect encoding detected in {}, please rebuild the dataset'.format(SCREAMING_SNAKE_CASE__ ) ) return A : str =f.readlines() A : int =self._load_meta(SCREAMING_SNAKE_CASE__ ) for line in lines[indices_start_line:]: try: A , A : Optional[int] =line.rstrip().rsplit(' ' , 1 ) if field == "#fairseq:overwrite": A : int =True A , A : Optional[Any] =line.rsplit(' ' , 1 ) else: A : Any =False A : Tuple =int(SCREAMING_SNAKE_CASE__ ) A : Optional[int] =line if word in self and not overwrite: raise RuntimeError( 'Duplicate word found when loading Dictionary: \'{}\'. ' 'Duplicate words can overwrite earlier ones by adding the ' '#fairseq:overwrite flag at the end of the corresponding row ' 'in the dictionary file. If using the Camembert model, please ' 'download an updated copy of the model file.'.format(SCREAMING_SNAKE_CASE__ ) ) self.add_symbol(SCREAMING_SNAKE_CASE__ , n=SCREAMING_SNAKE_CASE__ , overwrite=SCREAMING_SNAKE_CASE__ ) except ValueError: raise ValueError('Incorrect dictionary format, expected \'<token> <cnt> [flags]\'' ) def A__ ( lowercase: Union[str, Any] ) -> 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} A : int =dict((re.sub(r'@@$', '', lowercase ), v) if k.endswith('@@' ) else (re.sub(r'$', '</w>', lowercase ), v) for k, v in d.items() ) A : int ='<s> <pad> </s> <unk>'.split() # restore the special tokens for k in keep_keys: del da[F'{k}</w>'] A : List[Any] =d[k] # restore return da def A__ ( lowercase: Optional[int], lowercase: Optional[Any] ) -> str: # prep if not os.path.exists(lowercase ): raise ValueError(F'path {biogpt_checkpoint_path} does not exist!' ) os.makedirs(lowercase, exist_ok=lowercase ) print(F'Writing results to {pytorch_dump_folder_path}' ) # handle various types of models A : List[str] =os.path.join(lowercase, 'checkpoint.pt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {checkpoint_file} does not exist!' ) A : Optional[Any] =torch.load(lowercase, map_location='cpu' ) A : Any =chkpt['cfg']['model'] # dicts A : Any =os.path.join(lowercase, 'dict.txt' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {dict_file} does not exist!' ) A : Dict =Dictionary.load(lowercase ) A : Optional[Any] =rewrite_dict_keys(src_dict.indices ) A : Tuple =len(lowercase ) A : Any =os.path.join(lowercase, VOCAB_FILES_NAMES['vocab_file'] ) print(F'Generating {src_vocab_file} of {src_vocab_size} records' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # merges_file (bpecodes) A : List[str] =os.path.join(lowercase, 'bpecodes' ) if not os.path.isfile(lowercase ): raise ValueError(F'path to the file {bpecodes_file} does not exist!' ) A : List[str] =os.path.join(lowercase, VOCAB_FILES_NAMES['merges_file'] ) shutil.copyfile(lowercase, lowercase ) # model config A : Tuple =os.path.join(lowercase, 'config.json' ) A : Tuple ={ 'activation_dropout': args['activation_dropout'], 'architectures': ['BioGptForCausalLM'], 'attention_probs_dropout_prob': args['attention_dropout'], 'bos_token_id': 0, 'eos_token_id': 2, 'hidden_act': args['activation_fn'], 'hidden_dropout_prob': args['dropout'], 'hidden_size': args['decoder_embed_dim'], 'initializer_range': 0.02, 'intermediate_size': args['decoder_ffn_embed_dim'], 'layer_norm_eps': 1e-1_2, 'layerdrop': args['decoder_layerdrop'], 'max_position_embeddings': args['max_target_positions'], 'model_type': 'biogpt', 'num_attention_heads': args['decoder_attention_heads'], 'num_hidden_layers': args['decoder_layers'], 'pad_token_id': 1, 'scale_embedding': not args['no_scale_embedding'], 'tie_word_embeddings': args['share_decoder_input_output_embed'], 'vocab_size': src_vocab_size, } # good hparam defaults to start with print(F'Generating {biogpt_model_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # tokenizer config A : int =os.path.join(lowercase, lowercase ) A : List[str] ={ 'bos_token': '<s>', 'eos_token': '</s>', 'model_max_length': 1_024, 'pad_token': '<pad>', 'special_tokens_map_file': None, 'tokenizer_class': 'BioGptTokenizer', 'unk_token': '<unk>', } print(F'Generating {biogpt_tokenizer_config_file}' ) with open(lowercase, 'w', encoding='utf-8' ) as f: f.write(json.dumps(lowercase, ensure_ascii=lowercase, indent=lowercase ) ) # model A : List[Any] =chkpt['model'] # remove unneeded keys A : List[Any] =[ 'decoder.version', ] for k in ignore_keys: model_state_dict.pop(lowercase, lowercase ) A : str =list(model_state_dict.keys() ) for layer_name in layer_names: if layer_name.endswith('output_projection.weight' ): A : Union[str, Any] =model_state_dict.pop(lowercase ) else: A : List[str] =model_state_dict.pop(lowercase ) A : Any =BioGptConfig.from_pretrained(lowercase ) A : str =BioGptForCausalLM(lowercase ) # check that it loads ok model_new.load_state_dict(lowercase ) # save A : Tuple =os.path.join(lowercase, lowercase ) print(F'Generating {pytorch_weights_dump_path}' ) torch.save(lowercase, lowercase ) print('Conversion is done!' ) if __name__ == "__main__": _lowercase : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--biogpt_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.''' ) _lowercase : List[Any] =parser.parse_args() convert_biogpt_checkpoint_to_pytorch(args.biogpt_checkpoint_path, args.pytorch_dump_folder_path)
661
1
_lowercase : dict[tuple[int, int, int], int] ={} def A__ ( lowercase: int, lowercase: int, lowercase: int ) -> int: # if we are absent twice, or late 3 consecutive days, # no further prize strings are possible if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on A : int =(days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one A : Union[str, Any] =_calculate(days - 1, lowercase, late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 A : Dict =_calculate(days - 1, absent + 1, 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter A : int =_calculate(days - 1, lowercase, 0 ) A : Tuple =state_late + state_absent + state_ontime A : Tuple =prizestrings return prizestrings def A__ ( lowercase: int = 30 ) -> int: return _calculate(lowercase, absent=0, late=0 ) if __name__ == "__main__": print(solution())
661
import os from argparse import ArgumentParser, Namespace from ..data import SingleSentenceClassificationProcessor as Processor from ..pipelines import TextClassificationPipeline from ..utils import is_tf_available, is_torch_available, logging from . import BaseTransformersCLICommand if not is_tf_available() and not is_torch_available(): raise RuntimeError('''At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training''') # TF training parameters _lowercase : str =False _lowercase : Optional[Any] =False def A__ ( lowercase: Namespace ) -> Optional[int]: return TrainCommand(lowercase ) class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ ): '''simple docstring''' @staticmethod def SCREAMING_SNAKE_CASE_ ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> Dict: A : Optional[Any] =parser.add_parser('train' , help='CLI tool to train a model on a task.' ) train_parser.add_argument( '--train_data' , type=SCREAMING_SNAKE_CASE__ , required=SCREAMING_SNAKE_CASE__ , help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.' , ) train_parser.add_argument( '--column_label' , type=SCREAMING_SNAKE_CASE__ , default=0 , help='Column of the dataset csv file with example labels.' ) train_parser.add_argument( '--column_text' , type=SCREAMING_SNAKE_CASE__ , default=1 , help='Column of the dataset csv file with example texts.' ) train_parser.add_argument( '--column_id' , type=SCREAMING_SNAKE_CASE__ , default=2 , help='Column of the dataset csv file with example ids.' ) train_parser.add_argument( '--skip_first_row' , action='store_true' , help='Skip the first row of the csv file (headers).' ) train_parser.add_argument('--validation_data' , type=SCREAMING_SNAKE_CASE__ , default='' , help='path to validation dataset.' ) train_parser.add_argument( '--validation_split' , type=SCREAMING_SNAKE_CASE__ , default=0.1 , help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.' , ) train_parser.add_argument('--output' , type=SCREAMING_SNAKE_CASE__ , default='./' , help='path to saved the trained model.' ) train_parser.add_argument( '--task' , type=SCREAMING_SNAKE_CASE__ , default='text_classification' , help='Task to train the model on.' ) train_parser.add_argument( '--model' , type=SCREAMING_SNAKE_CASE__ , default='bert-base-uncased' , help='Model\'s name or path to stored model.' ) train_parser.add_argument('--train_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=32 , help='Batch size for training.' ) train_parser.add_argument('--valid_batch_size' , type=SCREAMING_SNAKE_CASE__ , default=64 , help='Batch size for validation.' ) train_parser.add_argument('--learning_rate' , type=SCREAMING_SNAKE_CASE__ , default=3e-5 , help='Learning rate.' ) train_parser.add_argument('--adam_epsilon' , type=SCREAMING_SNAKE_CASE__ , default=1e-08 , help='Epsilon for Adam optimizer.' ) train_parser.set_defaults(func=SCREAMING_SNAKE_CASE__ ) def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Namespace ) -> List[Any]: A : Optional[int] =logging.get_logger('transformers-cli/training' ) A : Dict ='tf' if is_tf_available() else 'torch' os.makedirs(args.output , exist_ok=SCREAMING_SNAKE_CASE__ ) A : Optional[Any] =args.output A : List[str] =args.column_label A : int =args.column_text A : Union[str, Any] =args.column_id self.logger.info(f'Loading {args.task} pipeline for {args.model}' ) if args.task == "text_classification": A : Optional[Any] =TextClassificationPipeline.from_pretrained(args.model ) elif args.task == "token_classification": raise NotImplementedError elif args.task == "question_answering": raise NotImplementedError self.logger.info(f'Loading dataset from {args.train_data}' ) A : Tuple =Processor.create_from_csv( args.train_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Dict =None if args.validation_data: self.logger.info(f'Loading validation dataset from {args.validation_data}' ) A : List[Any] =Processor.create_from_csv( args.validation_data , column_label=args.column_label , column_text=args.column_text , column_id=args.column_id , skip_first_row=args.skip_first_row , ) A : Optional[Any] =args.validation_split A : str =args.train_batch_size A : Any =args.valid_batch_size A : Dict =args.learning_rate A : List[str] =args.adam_epsilon def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: if self.framework == "tf": return self.run_tf() return self.run_torch() def SCREAMING_SNAKE_CASE_ ( self : int ) -> List[str]: raise NotImplementedError def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: self.pipeline.fit( self.train_dataset , validation_data=self.valid_dataset , validation_split=self.validation_split , learning_rate=self.learning_rate , adam_epsilon=self.adam_epsilon , train_batch_size=self.train_batch_size , valid_batch_size=self.valid_batch_size , ) # Save trained pipeline self.pipeline.save_pretrained(self.output )
661
1
import argparse import io import requests import torch from omegaconf import OmegaConf from diffusers import AutoencoderKL from diffusers.pipelines.stable_diffusion.convert_from_ckpt import ( assign_to_checkpoint, conv_attn_to_linear, create_vae_diffusers_config, renew_vae_attention_paths, renew_vae_resnet_paths, ) def A__ ( lowercase: List[Any], lowercase: Optional[int] ) -> Optional[Any]: A : List[str] =checkpoint A : int ={} A : str =vae_state_dict['encoder.conv_in.weight'] A : Any =vae_state_dict['encoder.conv_in.bias'] A : str =vae_state_dict['encoder.conv_out.weight'] A : Optional[int] =vae_state_dict['encoder.conv_out.bias'] A : str =vae_state_dict['encoder.norm_out.weight'] A : List[Any] =vae_state_dict['encoder.norm_out.bias'] A : List[str] =vae_state_dict['decoder.conv_in.weight'] A : Dict =vae_state_dict['decoder.conv_in.bias'] A : Optional[int] =vae_state_dict['decoder.conv_out.weight'] A : Tuple =vae_state_dict['decoder.conv_out.bias'] A : Any =vae_state_dict['decoder.norm_out.weight'] A : Optional[Any] =vae_state_dict['decoder.norm_out.bias'] A : Union[str, Any] =vae_state_dict['quant_conv.weight'] A : str =vae_state_dict['quant_conv.bias'] A : Tuple =vae_state_dict['post_quant_conv.weight'] A : Optional[Any] =vae_state_dict['post_quant_conv.bias'] # Retrieves the keys for the encoder down blocks only A : List[str] =len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'encoder.down' in layer} ) A : List[str] ={ layer_id: [key for key in vae_state_dict if F'down.{layer_id}' in key] for layer_id in range(lowercase ) } # Retrieves the keys for the decoder up blocks only A : List[Any] =len({'.'.join(layer.split('.' )[:3] ) for layer in vae_state_dict if 'decoder.up' in layer} ) A : Any ={ layer_id: [key for key in vae_state_dict if F'up.{layer_id}' in key] for layer_id in range(lowercase ) } for i in range(lowercase ): A : List[str] =[key for key in down_blocks[i] if F'down.{i}' in key and F'down.{i}.downsample' not in key] if F'encoder.down.{i}.downsample.conv.weight' in vae_state_dict: A : Union[str, Any] =vae_state_dict.pop( F'encoder.down.{i}.downsample.conv.weight' ) A : Dict =vae_state_dict.pop( F'encoder.down.{i}.downsample.conv.bias' ) A : List[str] =renew_vae_resnet_paths(lowercase ) A : Union[str, Any] ={'old': F'down.{i}.block', 'new': F'down_blocks.{i}.resnets'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) A : str =[key for key in vae_state_dict if 'encoder.mid.block' in key] A : int =2 for i in range(1, num_mid_res_blocks + 1 ): A : Optional[Any] =[key for key in mid_resnets if F'encoder.mid.block_{i}' in key] A : List[Any] =renew_vae_resnet_paths(lowercase ) A : List[str] ={'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) A : int =[key for key in vae_state_dict if 'encoder.mid.attn' in key] A : List[Any] =renew_vae_attention_paths(lowercase ) A : List[str] ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) conv_attn_to_linear(lowercase ) for i in range(lowercase ): A : List[str] =num_up_blocks - 1 - i A : Any =[ key for key in up_blocks[block_id] if F'up.{block_id}' in key and F'up.{block_id}.upsample' not in key ] if F'decoder.up.{block_id}.upsample.conv.weight' in vae_state_dict: A : Union[str, Any] =vae_state_dict[ F'decoder.up.{block_id}.upsample.conv.weight' ] A : int =vae_state_dict[ F'decoder.up.{block_id}.upsample.conv.bias' ] A : Tuple =renew_vae_resnet_paths(lowercase ) A : str ={'old': F'up.{block_id}.block', 'new': F'up_blocks.{i}.resnets'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) A : int =[key for key in vae_state_dict if 'decoder.mid.block' in key] A : List[Any] =2 for i in range(1, num_mid_res_blocks + 1 ): A : Union[str, Any] =[key for key in mid_resnets if F'decoder.mid.block_{i}' in key] A : List[str] =renew_vae_resnet_paths(lowercase ) A : Any ={'old': F'mid.block_{i}', 'new': F'mid_block.resnets.{i - 1}'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) A : Dict =[key for key in vae_state_dict if 'decoder.mid.attn' in key] A : Union[str, Any] =renew_vae_attention_paths(lowercase ) A : Union[str, Any] ={'old': 'mid.attn_1', 'new': 'mid_block.attentions.0'} assign_to_checkpoint(lowercase, lowercase, lowercase, additional_replacements=[meta_path], config=lowercase ) conv_attn_to_linear(lowercase ) return new_checkpoint def A__ ( lowercase: str, lowercase: str, ) -> Optional[Any]: # Only support V1 A : str =requests.get( ' https://raw.githubusercontent.com/CompVis/stable-diffusion/main/configs/stable-diffusion/v1-inference.yaml' ) A : Union[str, Any] =io.BytesIO(r.content ) A : Union[str, Any] =OmegaConf.load(lowercase ) A : str =512 A : Optional[int] ='cuda' if torch.cuda.is_available() else 'cpu' if checkpoint_path.endswith('safetensors' ): from safetensors import safe_open A : int ={} with safe_open(lowercase, framework='pt', device='cpu' ) as f: for key in f.keys(): A : str =f.get_tensor(lowercase ) else: A : Any =torch.load(lowercase, map_location=lowercase )['state_dict'] # Convert the VAE model. A : Optional[Any] =create_vae_diffusers_config(lowercase, image_size=lowercase ) A : Any =custom_convert_ldm_vae_checkpoint(lowercase, lowercase ) A : Optional[Any] =AutoencoderKL(**lowercase ) vae.load_state_dict(lowercase ) vae.save_pretrained(lowercase ) if __name__ == "__main__": _lowercase : Optional[int] =argparse.ArgumentParser() parser.add_argument('''--vae_pt_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the VAE.pt to convert.''') _lowercase : int =parser.parse_args() vae_pt_to_vae_diffuser(args.vae_pt_path, args.dump_path)
661
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Tuple=30 , SCREAMING_SNAKE_CASE__ : int=4_00 , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : str=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Any=1 / 2_55 , SCREAMING_SNAKE_CASE__ : int=True , ) -> Optional[int]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p A : Optional[Any] =size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} A : Union[str, Any] =parent A : Union[str, Any] =batch_size A : Union[str, Any] =num_channels A : int =min_resolution A : List[Any] =max_resolution A : Dict =do_resize A : Tuple =size A : List[str] =do_normalize A : List[Any] =image_mean A : Dict =image_std A : Any =do_rescale A : List[str] =rescale_factor A : Optional[Any] =do_pad def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> List[Any]: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict=False ) -> Dict: if not batched: A : Any =image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): A , A : Union[str, Any] =image.size else: A , A : Tuple =image.shape[1], image.shape[2] if w < h: A : Any =int(self.size['shortest_edge'] * h / w ) A : Any =self.size['shortest_edge'] elif w > h: A : Dict =self.size['shortest_edge'] A : Dict =int(self.size['shortest_edge'] * w / h ) else: A : List[str] =self.size['shortest_edge'] A : Dict =self.size['shortest_edge'] else: A : List[Any] =[] for image in image_inputs: A , A : int =self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A : str =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] A : Tuple =max(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Tuple: A : str =ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Tuple: A : Tuple =self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , 'size' ) ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : int =self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) A : str =self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=SCREAMING_SNAKE_CASE__ ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Optional[int]: pass def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing A : Union[str, Any] =self.image_processing_class(**self.image_processor_dict ) # create random PIL images A : Tuple =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input A : List[Any] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : List[str] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A , A : Union[str, Any] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A : str =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input A : Tuple =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Any =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : Optional[int] =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> List[str]: # Initialize image_processing A : Optional[Any] =self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A : Any =prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input A : Optional[int] =image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values A , A : Tuple =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A : Tuple =image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='pt' ).pixel_values A , A : int =self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE_ ( self : Any ) -> Union[str, Any]: # prepare image and target A : Union[str, Any] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: A : List[Any] =json.loads(f.read() ) A : Any ={'image_id': 3_97_69, 'annotations': target} # encode them A : str =ConditionalDetrImageProcessor.from_pretrained('microsoft/conditional-detr-resnet-50' ) A : Any =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Optional[Any] =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : List[str] =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Dict =torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : str =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : Dict =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : List[str] =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : Union[str, Any] =torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify orig_size A : List[Any] =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : int =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Tuple: # prepare image, target and masks_path A : List[str] =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: A : Optional[int] =json.loads(f.read() ) A : int ={'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} A : Optional[Any] =pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them A : List[Any] =ConditionalDetrImageProcessor(format='coco_panoptic' ) A : Union[str, Any] =image_processing(images=SCREAMING_SNAKE_CASE__ , annotations=SCREAMING_SNAKE_CASE__ , masks_path=SCREAMING_SNAKE_CASE__ , return_tensors='pt' ) # verify pixel values A : Dict =torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , SCREAMING_SNAKE_CASE__ ) A : Dict =torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) # verify area A : Optional[int] =torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , SCREAMING_SNAKE_CASE__ ) ) # verify boxes A : List[Any] =torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , SCREAMING_SNAKE_CASE__ ) A : Any =torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) # verify image_id A : List[Any] =torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , SCREAMING_SNAKE_CASE__ ) ) # verify is_crowd A : Any =torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , SCREAMING_SNAKE_CASE__ ) ) # verify class_labels A : str =torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , SCREAMING_SNAKE_CASE__ ) ) # verify masks A : int =82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , SCREAMING_SNAKE_CASE__ ) # verify orig_size A : Any =torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , SCREAMING_SNAKE_CASE__ ) ) # verify size A : str =torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , SCREAMING_SNAKE_CASE__ ) )
661
1
import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: return None class SCREAMING_SNAKE_CASE_ : '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int ) -> Dict: return None class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' lowercase : List[Any] = [ # (model_name, model_kwargs) ("bert-base-cased", {}), ("gpt2", {"use_cache": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Dict: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE__ , 'tf' , 12 , **SCREAMING_SNAKE_CASE__ ) @require_torch @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , **SCREAMING_SNAKE_CASE__ ) @require_torch @slow def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> List[Any]: from transformers import BertModel A : Union[str, Any] =['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(SCREAMING_SNAKE_CASE__ ) ) vocab_file.flush() A : Optional[Any] =BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: A : Any =BertModel(BertConfig(vocab_size=len(SCREAMING_SNAKE_CASE__ ) ) ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , SCREAMING_SNAKE_CASE__ ) @require_tf @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: A : Optional[int] =self._test_export(SCREAMING_SNAKE_CASE__ , 'tf' , 12 , **SCREAMING_SNAKE_CASE__ ) A : Dict =quantize(Path(SCREAMING_SNAKE_CASE__ ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE__ ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Dict: for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: A : Optional[Any] =self._test_export(SCREAMING_SNAKE_CASE__ , 'pt' , 12 , **SCREAMING_SNAKE_CASE__ ) A : int =quantize(SCREAMING_SNAKE_CASE__ ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(SCREAMING_SNAKE_CASE__ ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def SCREAMING_SNAKE_CASE_ ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str]=None , **SCREAMING_SNAKE_CASE__ : Any ) -> int: try: # Compute path with TemporaryDirectory() as tempdir: A : Union[str, Any] =Path(SCREAMING_SNAKE_CASE__ ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return path except Exception as e: self.fail(SCREAMING_SNAKE_CASE__ ) @require_torch @require_tokenizers @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: from transformers import BertModel A : Union[str, Any] =BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) A : Optional[int] =BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'pt' ) @require_tf @require_tokenizers @slow def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: from transformers import TFBertModel A : str =TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) A : List[str] =BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'tf' ) def SCREAMING_SNAKE_CASE_ ( self : int , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: A : Any =FeatureExtractionPipeline(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A : int =['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] A , A , A , A : Any =infer_shapes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Assert all variables are present self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , SCREAMING_SNAKE_CASE__ ) self.assertSequenceEqual(variable_names[3:] , SCREAMING_SNAKE_CASE__ ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: 'batch', 1: 'sequence'} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['output_0'] , {0: 'batch', 1: 'sequence'} ) self.assertDictEqual(shapes['output_1'] , {0: 'batch'} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : Dict =['input_ids', 'attention_mask', 'token_type_ids'] A : Optional[Any] ={'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} A , A : Optional[int] =ensure_valid_input(FuncContiguousArgs() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 3 ) # Should have exactly the same input names self.assertEqual(set(SCREAMING_SNAKE_CASE__ ) , set(SCREAMING_SNAKE_CASE__ ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(SCREAMING_SNAKE_CASE__ , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) A , A : List[Any] =ensure_valid_input(FuncNonContiguousArgs() , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['input_ids'] ) self.assertEqual(ordered_input_names[0] , 'input_ids' ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> List[str]: A : str =generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
661
import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler _lowercase : List[Any] =1_6 _lowercase : Union[str, Any] =3_2 def A__ ( lowercase: Accelerator, lowercase: int = 16, lowercase: str = "bert-base-cased" ) -> Optional[int]: A : List[Any] =AutoTokenizer.from_pretrained(lowercase ) A : Any =load_dataset('glue', 'mrpc' ) def tokenize_function(lowercase: Any ): # max_length=None => use the model max length (it's actually the default) A : List[str] =tokenizer(examples['sentence1'], examples['sentence2'], truncation=lowercase, max_length=lowercase ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset A : Any =datasets.map( lowercase, batched=lowercase, remove_columns=['idx', 'sentence1', 'sentence2'], load_from_cache_file=lowercase ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A : Dict =tokenized_datasets.rename_column('label', 'labels' ) def collate_fn(lowercase: 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(lowercase, padding='max_length', max_length=128, return_tensors='pt' ) return tokenizer.pad(lowercase, padding='longest', return_tensors='pt' ) # Instantiate dataloaders. A : Union[str, Any] =DataLoader( tokenized_datasets['train'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) A : str =DataLoader( tokenized_datasets['validation'], shuffle=lowercase, collate_fn=lowercase, batch_size=lowercase ) return train_dataloader, eval_dataloader def A__ ( lowercase: Dict, lowercase: Optional[int], lowercase: Any, lowercase: str ) -> Tuple: model.eval() A : Tuple =0 for step, batch in enumerate(lowercase ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A : Tuple =model(**lowercase ) A : Tuple =outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times A , A : Union[str, Any] =accelerator.gather( (predictions, batch['labels']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowercase ) - 1: A : List[Any] =predictions[: len(eval_dataloader.dataset ) - samples_seen] A : Optional[int] =references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowercase, references=lowercase, ) A : Union[str, Any] =metric.compute() return eval_metric["accuracy"] def A__ ( lowercase: Union[str, Any], lowercase: Dict ) -> List[str]: # Initialize accelerator A : Optional[int] =Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A : int =config['lr'] A : Optional[Any] =int(config['num_epochs'] ) A : Union[str, Any] =int(config['seed'] ) A : List[str] =int(config['batch_size'] ) A : Optional[Any] =args.model_name_or_path set_seed(lowercase ) A , A : str =get_dataloaders(lowercase, lowercase, lowercase ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A : List[str] =AutoModelForSequenceClassification.from_pretrained(lowercase, return_dict=lowercase ) # Instantiate optimizer A : Any =( AdamW if accelerator.state.deepspeed_plugin is None or 'optimizer' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) A : List[str] =optimizer_cls(params=model.parameters(), lr=lowercase ) if accelerator.state.deepspeed_plugin is not None: A : Optional[int] =accelerator.state.deepspeed_plugin.deepspeed_config[ 'gradient_accumulation_steps' ] else: A : Dict =1 A : Union[str, Any] =(len(lowercase ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): A : List[Any] =get_linear_schedule_with_warmup( optimizer=lowercase, num_warmup_steps=0, num_training_steps=lowercase, ) else: A : List[str] =DummyScheduler(lowercase, total_num_steps=lowercase, 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. A , A , A , A , A : Optional[int] =accelerator.prepare( lowercase, lowercase, lowercase, lowercase, lowercase ) # We need to keep track of how many total steps we have iterated over A : Tuple =0 # We also need to keep track of the stating epoch so files are named properly A : List[str] =0 A : Tuple =evaluate.load('glue', 'mrpc' ) A : Optional[int] =num_epochs if args.partial_train_epoch is not None: A : Dict =args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) A : List[Any] =args.resume_from_checkpoint.split('epoch_' )[1] A : List[Any] ='' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break A : Union[str, Any] =int(lowercase ) + 1 A : List[str] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) accelerator.print('resumed checkpoint performance:', lowercase ) accelerator.print('resumed checkpoint\'s scheduler\'s lr:', lr_scheduler.get_lr()[0] ) accelerator.print('resumed optimizers\'s lr:', optimizer.param_groups[0]['lr'] ) with open(os.path.join(args.output_dir, F'state_{starting_epoch-1}.json' ), 'r' ) as f: A : Union[str, Any] =json.load(lowercase ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model A : str ={} for epoch in range(lowercase, lowercase ): model.train() for step, batch in enumerate(lowercase ): A : Tuple =model(**lowercase ) A : List[Any] =outputs.loss A : Any =loss / gradient_accumulation_steps accelerator.backward(lowercase ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 A : Union[str, Any] =F'epoch_{epoch}' A : Optional[Any] =os.path.join(args.output_dir, lowercase ) accelerator.save_state(lowercase ) A : Optional[Any] =evaluation_loop(lowercase, lowercase, lowercase, lowercase ) A : Dict =accuracy A : Optional[Any] =lr_scheduler.get_lr()[0] A : Any =optimizer.param_groups[0]['lr'] A : str =epoch A : Dict =overall_step accelerator.print(F'epoch {epoch}:', lowercase ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F'state_{epoch}.json' ), 'w' ) as f: json.dump(lowercase, lowercase ) def A__ ( ) -> Optional[int]: A : Optional[int] =argparse.ArgumentParser(description='Simple example of training script tracking peak GPU memory usage.' ) parser.add_argument( '--model_name_or_path', type=lowercase, default='bert-base-cased', help='Path to pretrained model or model identifier from huggingface.co/models.', required=lowercase, ) parser.add_argument( '--output_dir', type=lowercase, default='.', help='Optional save directory where all checkpoint folders will be stored. Default is the current working directory.', ) parser.add_argument( '--resume_from_checkpoint', type=lowercase, default=lowercase, help='If the training should continue from a checkpoint folder.', ) parser.add_argument( '--partial_train_epoch', type=lowercase, default=lowercase, help='If passed, the training will stop after this number of epochs.', ) parser.add_argument( '--num_epochs', type=lowercase, default=2, help='Number of train epochs.', ) A : str =parser.parse_args() A : Optional[int] ={'lr': 2e-5, 'num_epochs': args.num_epochs, 'seed': 42, 'batch_size': 16} training_function(lowercase, lowercase ) if __name__ == "__main__": main()
661
1
import json import os import unittest from transformers.models.gptsan_japanese.tokenization_gptsan_japanese import ( VOCAB_FILES_NAMES, GPTSanJapaneseTokenizer, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class SCREAMING_SNAKE_CASE_ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' lowercase : Dict = GPTSanJapaneseTokenizer lowercase : str = False lowercase : Optional[int] = {"do_clean_text": False, "add_prefix_space": False} def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Tuple: super().setUp() # fmt: off A : Dict =['ใ“ใ‚“', 'ใ“ใ‚“ใซ', 'ใซใกใฏ', 'ใฐใ‚“ใฏ', 'ไธ–็•Œ,ใ”บ็•Œ', 'ใ€', 'ใ€‚', '<BR>', '<SP>', '<TAB>', '<URL>', '<EMAIL>', '<TEL>', '<DATE>', '<PRICE>', '<BLOCK>', '<KIGOU>', '<U2000U2BFF>', '<|emoji1|>', '<unk>', '<|bagoftoken|>', '<|endoftext|>'] # fmt: on A : Union[str, Any] ={'emoji': {'\ud83d\ude00': '<|emoji1|>'}, 'emoji_inv': {'<|emoji1|>': '\ud83d\ude00'}} # ๐Ÿ˜€ A : Optional[int] ={'unk_token': '<unk>'} A : Optional[int] =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) A : int =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['emoji_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) with open(self.emoji_file , 'w' ) as emoji_writer: emoji_writer.write(json.dumps(SCREAMING_SNAKE_CASE__ ) ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: kwargs.update(self.special_tokens_map ) return GPTSanJapaneseTokenizer.from_pretrained(self.tmpdirname , **SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: A : Dict ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' A : Union[str, Any] ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ \nใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' return input_text, output_text def SCREAMING_SNAKE_CASE_ ( self : List[str] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: A , A : Optional[int] =self.get_input_output_texts(SCREAMING_SNAKE_CASE__ ) A : Union[str, Any] =tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) A : Any =tokenizer.decode(SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) return text, ids def SCREAMING_SNAKE_CASE_ ( self : int ) -> Union[str, Any]: pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> str: pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Tuple: pass # TODO add if relevant def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Dict: A : int =self.get_tokenizer() # Testing tokenization A : str ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ€€ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚' A : Any =['ใ“ใ‚“', 'ใซใกใฏ', 'ใ€', 'ไธ–็•Œ', 'ใ€‚', '<SP>', 'ใ“ใ‚“', 'ใฐใ‚“ใฏ', 'ใ€', 'ใ”บ็•Œ', 'ใ€‚'] A : Any =tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids without special tokens A : Any =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6] A : Union[str, Any] =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # Testing conversion to ids with special tokens A : Optional[int] =tokens + [tokenizer.unk_token] A : int =[0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19] A : int =tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> str: A : int =self.get_tokenizer() # Testing tokenization A : Any ='ใ“ใ‚“ใซใกใฏใ€<|bagoftoken|>ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€<|bagoftoken|>ใ”บ็•Œใ€‚' A : Optional[Any] ='ใ“ใ‚“ใซใกใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ใ€ใ€ใ€ไธ–็•Œใ€‚' A : Optional[Any] =tokenizer.encode(SCREAMING_SNAKE_CASE__ ) A : int =tokenizer.decode(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> int: A : Union[str, Any] =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization A : List[str] ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' A : List[Any] ='ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' A : Dict ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚ใ“ใ‚“ใฐใ‚“ใฏใ€ไธ–็•Œใ€‚๐Ÿ˜€' A : List[Any] =tokenizer.encode(prefix_text + input_text ) A : Optional[int] =tokenizer.encode('' , prefix_text=prefix_text + input_text ) A : List[str] =tokenizer.encode(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.decode(SCREAMING_SNAKE_CASE__ ) A : Tuple =tokenizer.decode(SCREAMING_SNAKE_CASE__ ) A : List[Any] =tokenizer.decode(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__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[Any]: A : str =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) # Testing tokenization A : int ='ใ“ใ‚“ใซใกใฏใ€ไธ–็•Œใ€‚' A : Optional[int] ='ใ“ใ‚“ใฐใ‚“ใฏใ€ใ”บ็•Œใ€‚๐Ÿ˜€' A : str =len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 A : Optional[int] =len(tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) - 2 A : Union[str, Any] =[1] + [0] * (len_prefix + len_text + 1) A : str =[1] * (len_prefix + len_text + 1) + [0] A : str =[1] + [1] * (len_prefix) + [0] * (len_text + 1) A : Union[str, Any] =tokenizer(prefix_text + input_text ).token_type_ids A : Tuple =tokenizer('' , prefix_text=prefix_text + input_text ).token_type_ids A : str =tokenizer(SCREAMING_SNAKE_CASE__ , prefix_text=SCREAMING_SNAKE_CASE__ ).token_type_ids self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> Optional[Any]: A : Tuple =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) A : int =tokenizer.encode('ใ‚ใƒณใ„ใƒฏ' ) A : int =tokenizer.encode('' , prefix_text='ใ‚ใƒณใ„ใƒฏ' ) A : int =tokenizer.encode('ใ„ใƒฏ' , prefix_text='ใ‚ใƒณ' ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertEqual(tokenizer.decode(SCREAMING_SNAKE_CASE__ ) , tokenizer.decode(SCREAMING_SNAKE_CASE__ ) ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertNotEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.assertEqual(x_token_a[1] , x_token_a[-1] ) # SEG token self.assertEqual(x_token_a[1] , x_token_a[3] ) # SEG token @slow def SCREAMING_SNAKE_CASE_ ( self : str ) -> Tuple: A : str =self.tokenizer_class.from_pretrained('Tanrei/GPTSAN-japanese' ) A : str =[['ๆญฆ็”ฐไฟก็Ž„', 'ใฏใ€'], ['็น”็”ฐไฟก้•ท', 'ใฎ้…ไธ‹ใฎใ€']] A : Optional[int] =tokenizer(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) A : str =tokenizer.batch_encode_plus(SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ ) # fmt: off A : Dict =[[3_59_93, 86_40, 2_59_48, 3_59_98, 3_06_47, 3_56_75, 3_59_99, 3_59_99], [3_59_93, 1_03_82, 98_68, 3_59_98, 3_06_46, 94_59, 3_06_46, 3_56_75]] A : int =[[1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0]] A : int =[[1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1]] # fmt: on self.assertListEqual(x_token.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token.attention_mask , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.input_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.token_type_ids , SCREAMING_SNAKE_CASE__ ) self.assertListEqual(x_token_a.attention_mask , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> int: # Intentionally convert some words to accommodate character fluctuations unique to Japanese pass def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Dict: # tokenizer has no padding token pass
661
def A__ ( lowercase: int ) -> int: if not isinstance(lowercase, lowercase ) or number < 0: raise ValueError('Input must be a non-negative integer' ) A : Any =0 while number: # This way we arrive at next set bit (next 1) instead of looping # through each bit and checking for 1s hence the # loop won't run 32 times it will only run the number of `1` times number &= number - 1 count += 1 return count if __name__ == "__main__": import doctest doctest.testmod()
661
1
import unittest from transformers.testing_utils import CaptureStdout from transformers.tools.python_interpreter import evaluate def A__ ( lowercase: List[Any] ) -> Dict: return x + 2 class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE_ ( self : str ) -> Optional[Any]: A : Union[str, Any] ='x = 3' A : Tuple ={} A : List[str] =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3} ) A : Any ='x = y' A : int ={'y': 5} A : int =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 5, 'y': 5} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> List[str]: A : Any ='y = add_two(x)' A : List[Any] ={'x': 3} A : Tuple =evaluate(SCREAMING_SNAKE_CASE__ , {'add_two': add_two} , state=SCREAMING_SNAKE_CASE__ ) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'y': 5} ) # Won't work without the tool with CaptureStdout() as out: A : Dict =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) assert result is None assert "tried to execute add_two" in out.out def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> Dict: A : int ='x = 3' A : int ={} A : Optional[Any] =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] ) -> Any: A : Tuple ='test_dict = {\'x\': x, \'y\': add_two(x)}' A : Union[str, Any] ={'x': 3} A : int =evaluate(SCREAMING_SNAKE_CASE__ , {'add_two': add_two} , state=SCREAMING_SNAKE_CASE__ ) self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'y': 5} ) self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'test_dict': {'x': 3, 'y': 5}} ) def SCREAMING_SNAKE_CASE_ ( self : Dict ) -> Optional[Any]: A : str ='x = 3\ny = 5' A : int ={} A : Union[str, Any] =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'y': 5} ) def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] ) -> List[Any]: A : Dict ='text = f\'This is x: {x}.\'' A : Optional[int] ={'x': 3} A : Tuple =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) # evaluate returns the value of the last assignment. assert result == "This is x: 3." self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'text': 'This is x: 3.'} ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> Optional[Any]: A : Union[str, Any] ='if x <= 3:\n y = 2\nelse:\n y = 5' A : Optional[int] ={'x': 3} A : Optional[int] =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) # evaluate returns the value of the last assignment. assert result == 2 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'y': 2} ) A : Union[str, Any] ={'x': 8} A : str =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) # evaluate returns the value of the last assignment. assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 8, 'y': 5} ) def SCREAMING_SNAKE_CASE_ ( self : Tuple ) -> Dict: A : Tuple ='test_list = [x, add_two(x)]' A : Union[str, Any] ={'x': 3} A : Tuple =evaluate(SCREAMING_SNAKE_CASE__ , {'add_two': add_two} , state=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , [3, 5] ) self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'test_list': [3, 5]} ) def SCREAMING_SNAKE_CASE_ ( self : List[str] ) -> str: A : Optional[Any] ='y = x' A : List[str] ={'x': 3} A : Any =evaluate(SCREAMING_SNAKE_CASE__ , {} , state=SCREAMING_SNAKE_CASE__ ) assert result == 3 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'y': 3} ) def SCREAMING_SNAKE_CASE_ ( self : List[Any] ) -> List[str]: A : Optional[Any] ='test_list = [x, add_two(x)]\ntest_list[1]' A : Any ={'x': 3} A : List[Any] =evaluate(SCREAMING_SNAKE_CASE__ , {'add_two': add_two} , state=SCREAMING_SNAKE_CASE__ ) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'test_list': [3, 5]} ) A : Any ='test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']' A : Optional[int] ={'x': 3} A : Any =evaluate(SCREAMING_SNAKE_CASE__ , {'add_two': add_two} , state=SCREAMING_SNAKE_CASE__ ) assert result == 5 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 3, 'test_dict': {'x': 3, 'y': 5}} ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] ) -> Any: A : Union[str, Any] ='x = 0\nfor i in range(3):\n x = i' A : Dict ={} A : Union[str, Any] =evaluate(SCREAMING_SNAKE_CASE__ , {'range': range} , state=SCREAMING_SNAKE_CASE__ ) assert result == 2 self.assertDictEqual(SCREAMING_SNAKE_CASE__ , {'x': 2, 'i': 2} )
661
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def A__ ( *lowercase: Tuple, lowercase: Optional[Union[Dict, Any]] = None, lowercase: Dict=True, lowercase: Any=2 ) -> List[Any]: from .. import __version__ A : Optional[Any] =take_from A : Union[str, Any] =() if not isinstance(args[0], lowercase ): A : List[str] =(args,) for attribute, version_name, message in args: if version.parse(version.parse(lowercase ).base_version ) >= version.parse(lowercase ): raise ValueError( F'The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers\'' F' version {__version__} is >= {version_name}' ) A : Tuple =None if isinstance(lowercase, lowercase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(lowercase ),) A : Union[str, Any] =F'The `{attribute}` argument is deprecated and will be removed in version {version_name}.' elif hasattr(lowercase, lowercase ): values += (getattr(lowercase, lowercase ),) A : Optional[Any] =F'The `{attribute}` attribute is deprecated and will be removed in version {version_name}.' elif deprecated_kwargs is None: A : List[Any] =F'`{attribute}` is deprecated and will be removed in version {version_name}.' if warning is not None: A : List[Any] =warning + ' ' if standard_warn else '' warnings.warn(warning + message, lowercase, stacklevel=lowercase ) if isinstance(lowercase, lowercase ) and len(lowercase ) > 0: A : Any =inspect.getouterframes(inspect.currentframe() )[1] A : int =call_frame.filename A : int =call_frame.lineno A : Optional[int] =call_frame.function A , A : int =next(iter(deprecated_kwargs.items() ) ) raise TypeError(F'{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`' ) if len(lowercase ) == 0: return elif len(lowercase ) == 1: return values[0] return values
661
1