code
stringlengths
82
53.2k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __A : List[str] = logging.get_logger(__name__) __A : List[Any] = {"vocab_file": "spiece.model"} __A : Dict = { "vocab_file": { "bert_for_seq_generation": ( "https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model" ), } } __A : str = {"bert_for_seq_generation": 512} class lowerCamelCase( __snake_case ): '''simple docstring''' __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = [] __magic_name__ = ['input_ids', 'attention_mask'] def __init__( self , snake_case_ , snake_case_="<s>" , snake_case_="</s>" , snake_case_="<unk>" , snake_case_="<pad>" , snake_case_="<::::>" , snake_case_ = None , **snake_case_ , ): _A = {} if sp_model_kwargs is None else sp_model_kwargs # Add extra_ids to the special token list super().__init__( bos_token=snake_case_ , eos_token=snake_case_ , unk_token=snake_case_ , pad_token=snake_case_ , sep_token=snake_case_ , sp_model_kwargs=self.sp_model_kwargs , **snake_case_ , ) _A = vocab_file _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(snake_case_ ) @property def lowerCAmelCase__ ( self ): return self.sp_model.get_piece_size() def lowerCAmelCase__ ( self ): _A = {self.convert_ids_to_tokens(snake_case_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): _A = self.__dict__.copy() _A = None return state def __setstate__( self , snake_case_ ): _A = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): _A = {} _A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCAmelCase__ ( self , snake_case_ ): return self.sp_model.encode(snake_case_ , out_type=snake_case_ ) def lowerCAmelCase__ ( self , snake_case_ ): return self.sp_model.piece_to_id(snake_case_ ) def lowerCAmelCase__ ( self , snake_case_ ): _A = self.sp_model.IdToPiece(snake_case_ ) return token def lowerCAmelCase__ ( self , snake_case_ ): _A = [] _A = '' 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(snake_case_ ) + token _A = [] else: current_sub_tokens.append(snake_case_ ) out_string += self.sp_model.decode(snake_case_ ) return out_string.strip() def lowerCAmelCase__ ( self , snake_case_ , snake_case_ = None ): if not os.path.isdir(snake_case_ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return _A = os.path.join( snake_case_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(snake_case_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , snake_case_ ) elif not os.path.isfile(self.vocab_file ): with open(snake_case_ , 'wb' ) as fi: _A = self.sp_model.serialized_model_proto() fi.write(snake_case_ ) return (out_vocab_file,)
27
import unittest from transformers import AutoTokenizer, NystromformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase: '''simple docstring''' def __init__( self , snake_case_ , snake_case_=13 , snake_case_=7 , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=True , snake_case_=99 , snake_case_=32 , snake_case_=5 , snake_case_=4 , snake_case_=37 , snake_case_="gelu" , snake_case_=0.1 , snake_case_=0.1 , snake_case_=512 , snake_case_=16 , snake_case_=2 , snake_case_=0.02 , snake_case_=3 , snake_case_=4 , snake_case_=None , ): _A = parent _A = batch_size _A = seq_length _A = is_training _A = use_input_mask _A = use_token_type_ids _A = use_labels _A = vocab_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = type_vocab_size _A = type_sequence_label_size _A = initializer_range _A = num_labels _A = num_choices _A = scope def lowerCAmelCase__ ( self ): _A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A = None if self.use_input_mask: _A = random_attention_mask([self.batch_size, self.seq_length] ) _A = None if self.use_token_type_ids: _A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _A = None _A = None _A = None if self.use_labels: _A = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _A = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _A = ids_tensor([self.batch_size] , self.num_choices ) _A = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCAmelCase__ ( self ): return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=snake_case_ , initializer_range=self.initializer_range , ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = NystromformerModel(config=snake_case_ ) model.to(snake_case_ ) model.eval() _A = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ ) _A = model(snake_case_ , token_type_ids=snake_case_ ) _A = model(snake_case_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = NystromformerForMaskedLM(config=snake_case_ ) model.to(snake_case_ ) model.eval() _A = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = NystromformerForQuestionAnswering(config=snake_case_ ) model.to(snake_case_ ) model.eval() _A = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , start_positions=snake_case_ , end_positions=snake_case_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = self.num_labels _A = NystromformerForSequenceClassification(snake_case_ ) model.to(snake_case_ ) model.eval() _A = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = self.num_labels _A = NystromformerForTokenClassification(config=snake_case_ ) model.to(snake_case_ ) model.eval() _A = model(snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCAmelCase__ ( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ): _A = self.num_choices _A = NystromformerForMultipleChoice(config=snake_case_ ) model.to(snake_case_ ) model.eval() _A = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _A = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _A = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _A = model( snake_case_ , attention_mask=snake_case_ , token_type_ids=snake_case_ , labels=snake_case_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCAmelCase__ ( self ): _A = self.prepare_config_and_inputs() ( ( _A ), ( _A ), ( _A ), ( _A ), ( _A ), ( _A ), ( _A ), ) = config_and_inputs _A = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class lowerCamelCase( __snake_case , __snake_case , unittest.TestCase ): '''simple docstring''' __magic_name__ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) __magic_name__ = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) __magic_name__ = False __magic_name__ = False def lowerCAmelCase__ ( self ): _A = NystromformerModelTester(self ) _A = ConfigTester(self , config_class=snake_case_ , hidden_size=37 ) def lowerCAmelCase__ ( self ): self.config_tester.run_common_tests() def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _A = type self.model_tester.create_and_check_model(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*snake_case_ ) def lowerCAmelCase__ ( self ): _A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*snake_case_ ) @slow def lowerCAmelCase__ ( self ): for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _A = NystromformerModel.from_pretrained(snake_case_ ) self.assertIsNotNone(snake_case_ ) @require_torch class lowerCamelCase( unittest.TestCase ): '''simple docstring''' @slow def lowerCAmelCase__ ( self ): _A = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) _A = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): _A = model(snake_case_ )[0] _A = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , snake_case_ ) _A = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , snake_case_ , atol=1E-4 ) ) @slow def lowerCAmelCase__ ( self ): _A = 'the [MASK] of Belgium is Brussels' _A = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) _A = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) _A = tokenizer(snake_case_ , return_tensors='pt' ) with torch.no_grad(): _A = model(encoding.input_ids ).logits _A = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(snake_case_ ) , 'capital' )
27
1
'''simple docstring''' import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def UpperCAmelCase_ ( lowercase__ = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError("number of qubits must be a integer." ) if number_of_qubits <= 0: raise ValueError("number of qubits must be > 0." ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError("number of qubits must be exact integer." ) if number_of_qubits > 1_0: raise ValueError("number of qubits too large to simulate(>10)." ) a_ =QuantumRegister(lowercase__ , "qr" ) a_ =ClassicalRegister(lowercase__ , "cr" ) a_ =QuantumCircuit(lowercase__ , lowercase__ ) a_ =number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots a_ =Aer.get_backend("qasm_simulator" ) a_ =execute(lowercase__ , lowercase__ , shots=1_0_0_0_0 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
41
'''simple docstring''' import os # Precomputes a list of the 100 first triangular numbers lowercase = [int(0.5 * n * (n + 1)) for n in range(1, 101)] def UpperCAmelCase_ ( ): '''simple docstring''' a_ =os.path.dirname(os.path.realpath(lowercase__ ) ) a_ =os.path.join(lowercase__ , "words.txt" ) a_ ="" with open(lowercase__ ) as f: a_ =f.readline() a_ =[word.strip("\"" ) for word in words.strip("\r\n" ).split("," )] a_ =[ word for word in [sum(ord(lowercase__ ) - 6_4 for x in word ) for word in words] if word in TRIANGULAR_NUMBERS ] return len(lowercase__ ) if __name__ == "__main__": print(solution())
41
1
import os def a ( ): '''simple docstring''' with open(os.path.dirname(snake_case__ ) + '''/grid.txt''' ) as f: lowercase_ = [] # noqa: E741 for _ in range(20 ): l.append([int(snake_case__ ) for x in f.readline().split()] ) lowercase_ = 0 # right for i in range(20 ): for j in range(17 ): lowercase_ = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: lowercase_ = temp # down for i in range(17 ): for j in range(20 ): lowercase_ = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: lowercase_ = temp # diagonal 1 for i in range(17 ): for j in range(17 ): lowercase_ = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: lowercase_ = temp # diagonal 2 for i in range(17 ): for j in range(3 , 20 ): lowercase_ = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: lowercase_ = temp return maximum if __name__ == "__main__": print(solution())
97
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging __UpperCAmelCase = logging.get_logger(__name__) class lowercase_ ( a_ ): def __init__( self : int , _lowercase : List[str]=None , **_lowercase : List[str] ): warnings.warn( "`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` " "instead." , _lowercase , ) super().__init__(args=_lowercase , **_lowercase )
308
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import AlignProcessor, EfficientNetImageProcessor @require_vision class _UpperCamelCase ( unittest.TestCase ): """simple docstring""" def _SCREAMING_SNAKE_CASE ( self ) -> Tuple: '''simple docstring''' __lowercase = tempfile.mkdtemp() __lowercase = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __lowercase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __lowercase = { '''do_resize''': True, '''size''': 20, '''do_center_crop''': True, '''crop_size''': 18, '''do_normalize''': True, '''image_mean''': [0.4814_5466, 0.457_8275, 0.4082_1073], '''image_std''': [0.2686_2954, 0.2613_0258, 0.2757_7711], } __lowercase = os.path.join(self.tmpdirname , lowerCAmelCase__ ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , **lowerCAmelCase__ ) -> int: '''simple docstring''' return BertTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , **lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , **lowerCAmelCase__ ) -> Tuple: '''simple docstring''' return EfficientNetImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowercase = [Image.fromarray(np.moveaxis(lowerCAmelCase__ , 0 , -1 ) ) for x in image_inputs] return image_inputs def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.get_tokenizer() __lowercase = self.get_rust_tokenizer() __lowercase = self.get_image_processor() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_slow.save_pretrained(self.tmpdirname ) __lowercase = AlignProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase__ ) __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) processor_fast.save_pretrained(self.tmpdirname ) __lowercase = AlignProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase__ ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = AlignProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowercase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __lowercase = self.get_image_processor(do_normalize=lowerCAmelCase__ , padding_value=1.0 ) __lowercase = AlignProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=lowerCAmelCase__ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowerCAmelCase__ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Dict: '''simple docstring''' __lowercase = self.get_image_processor() __lowercase = self.get_tokenizer() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __lowercase = self.prepare_image_inputs() __lowercase = image_processor(lowerCAmelCase__ , return_tensors='''np''' ) __lowercase = processor(images=lowerCAmelCase__ , return_tensors='''np''' ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1E-2 ) def _SCREAMING_SNAKE_CASE ( self ) -> List[Any]: '''simple docstring''' __lowercase = self.get_image_processor() __lowercase = self.get_tokenizer() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __lowercase = '''lower newer''' __lowercase = processor(text=lowerCAmelCase__ ) __lowercase = tokenizer(lowerCAmelCase__ , padding='''max_length''' , max_length=64 ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _SCREAMING_SNAKE_CASE ( self ) -> List[str]: '''simple docstring''' __lowercase = self.get_image_processor() __lowercase = self.get_tokenizer() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __lowercase = '''lower newer''' __lowercase = self.prepare_image_inputs() __lowercase = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase__ ): processor() def _SCREAMING_SNAKE_CASE ( self ) -> str: '''simple docstring''' __lowercase = self.get_image_processor() __lowercase = self.get_tokenizer() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __lowercase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowercase = processor.batch_decode(lowerCAmelCase__ ) __lowercase = tokenizer.batch_decode(lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.get_image_processor() __lowercase = self.get_tokenizer() __lowercase = AlignProcessor(tokenizer=lowerCAmelCase__ , image_processor=lowerCAmelCase__ ) __lowercase = '''lower newer''' __lowercase = self.prepare_image_inputs() __lowercase = processor(text=lowerCAmelCase__ , images=lowerCAmelCase__ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
522
from ...processing_utils import ProcessorMixin class _UpperCamelCase ( _UpperCAmelCase ): """simple docstring""" __a : Tuple = '''SpeechT5FeatureExtractor''' __a : Optional[Any] = '''SpeechT5Tokenizer''' def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Dict: '''simple docstring''' super().__init__(lowerCAmelCase__ , lowerCAmelCase__ ) def __call__( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> str: '''simple docstring''' __lowercase = kwargs.pop('''audio''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''text''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''text_target''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''audio_target''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''sampling_rate''' , lowerCAmelCase__ ) if audio is not None and text is not None: raise ValueError( '''Cannot process both `audio` and `text` inputs. Did you mean `audio_target` or `text_target`?''' ) if audio_target is not None and text_target is not None: raise ValueError( '''Cannot process both `audio_target` and `text_target` inputs. Did you mean `audio` or `text`?''' ) if audio is None and audio_target is None and text is None and text_target is None: raise ValueError( '''You need to specify either an `audio`, `audio_target`, `text`, or `text_target` input to process.''' ) if audio is not None: __lowercase = self.feature_extractor(lowerCAmelCase__ , *lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , **lowerCAmelCase__ ) elif text is not None: __lowercase = self.tokenizer(lowerCAmelCase__ , **lowerCAmelCase__ ) else: __lowercase = None if audio_target is not None: __lowercase = self.feature_extractor(audio_target=lowerCAmelCase__ , *lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , **lowerCAmelCase__ ) __lowercase = targets['''input_values'''] elif text_target is not None: __lowercase = self.tokenizer(lowerCAmelCase__ , **lowerCAmelCase__ ) __lowercase = targets['''input_ids'''] else: __lowercase = None if inputs is None: return targets if targets is not None: __lowercase = labels __lowercase = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: __lowercase = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' __lowercase = kwargs.pop('''input_values''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''input_ids''' , lowerCAmelCase__ ) __lowercase = kwargs.pop('''labels''' , lowerCAmelCase__ ) if input_values is not None and input_ids is not None: raise ValueError('''Cannot process both `input_values` and `input_ids` inputs.''' ) if input_values is None and input_ids is None and labels is None: raise ValueError( '''You need to specify either an `input_values`, `input_ids`, or `labels` input to be padded.''' ) if input_values is not None: __lowercase = self.feature_extractor.pad(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) elif input_ids is not None: __lowercase = self.tokenizer.pad(lowerCAmelCase__ , **lowerCAmelCase__ ) else: __lowercase = None if labels is not None: if "input_ids" in labels or (isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and "input_ids" in labels[0]): __lowercase = self.tokenizer.pad(lowerCAmelCase__ , **lowerCAmelCase__ ) __lowercase = targets['''input_ids'''] else: __lowercase = self.feature_extractor.feature_size __lowercase = self.feature_extractor.num_mel_bins __lowercase = self.feature_extractor.pad(lowerCAmelCase__ , *lowerCAmelCase__ , **lowerCAmelCase__ ) __lowercase = feature_size_hack __lowercase = targets['''input_values'''] else: __lowercase = None if inputs is None: return targets if targets is not None: __lowercase = labels __lowercase = targets.get('''attention_mask''' ) if decoder_attention_mask is not None: __lowercase = decoder_attention_mask return inputs def _SCREAMING_SNAKE_CASE ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> int: '''simple docstring''' return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ ) def _SCREAMING_SNAKE_CASE ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ) -> Any: '''simple docstring''' return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
522
1
"""simple docstring""" def _lowerCamelCase ( __a = 100 ): SCREAMING_SNAKE_CASE_ = set() SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = n + 1 # maximum limit for a in range(2, __a ): for b in range(2, __a ): SCREAMING_SNAKE_CASE_ = a**b # calculates the current power collect_powers.add(__a ) # adds the result to the set return len(__a ) if __name__ == "__main__": print('Number of terms ', solution(int(str(input()).strip())))
626
"""simple docstring""" from __future__ import annotations def _lowerCamelCase ( __a, __a = None ): SCREAMING_SNAKE_CASE_ = word_bank or [] # create a table SCREAMING_SNAKE_CASE_ = len(__a ) + 1 SCREAMING_SNAKE_CASE_ = [] for _ in range(__a ): table.append([] ) # seed value SCREAMING_SNAKE_CASE_ = [[]] # because empty string has empty combination # iterate through the indices for i in range(__a ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(__a )] == word: SCREAMING_SNAKE_CASE_ = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(__a )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(__a )]: combination.reverse() return table[len(__a )] if __name__ == "__main__": print(all_construct('jwajalapa', ['jwa', 'j', 'w', 'a', 'la', 'lapa'])) print(all_construct('rajamati', ['s', 'raj', 'amat', 'raja', 'ma', 'i', 't'])) print( all_construct( 'hexagonosaurus', ['h', 'ex', 'hex', 'ag', 'ago', 'ru', 'auru', 'rus', 'go', 'no', 'o', 's'], ) )
626
1
'''simple docstring''' from __future__ import annotations class a : def __init__( self , _lowerCAmelCase = 0 ): """simple docstring""" __SCREAMING_SNAKE_CASE: Tuple = key def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) __SCREAMING_SNAKE_CASE: Dict = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(snake_case_ ) ^ key ) for ch in content] def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) __SCREAMING_SNAKE_CASE: Tuple = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(snake_case_ ) ^ key ) for ch in content] def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase = 0 ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) __SCREAMING_SNAKE_CASE: Optional[int] = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned __SCREAMING_SNAKE_CASE: Optional[Any] = "" for ch in content: ans += chr(ord(snake_case_ ) ^ key ) return ans def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase = 0 ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) __SCREAMING_SNAKE_CASE: int = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned __SCREAMING_SNAKE_CASE: List[str] = "" for ch in content: ans += chr(ord(snake_case_ ) ^ key ) return ans def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase = 0 ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) try: with open(snake_case_ ) as fin, open('''encrypt.out''' , '''w+''' ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(snake_case_ , snake_case_ ) ) except OSError: return False return True def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase ): """simple docstring""" assert isinstance(snake_case_ , snake_case_ ) and isinstance(snake_case_ , snake_case_ ) try: with open(snake_case_ ) as fin, open('''decrypt.out''' , '''w+''' ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(snake_case_ , snake_case_ ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
721
import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class a ( __lowercase ): SCREAMING_SNAKE_CASE__ : List[Any] = (EulerDiscreteScheduler,) SCREAMING_SNAKE_CASE__ : Any = 10 def snake_case_ ( self , **_lowerCAmelCase ): """simple docstring""" __SCREAMING_SNAKE_CASE: str = { '''num_train_timesteps''': 1100, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**_lowerCAmelCase ) return config def snake_case_ ( self ): """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=_lowerCAmelCase ) def snake_case_ ( self ): """simple docstring""" for beta_start, beta_end in zip([0.00001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=_lowerCAmelCase , beta_end=_lowerCAmelCase ) def snake_case_ ( self ): """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=_lowerCAmelCase ) def snake_case_ ( self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=_lowerCAmelCase ) def snake_case_ ( self ): """simple docstring""" __SCREAMING_SNAKE_CASE: str = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE: Optional[int] = self.get_scheduler_config() __SCREAMING_SNAKE_CASE: List[str] = scheduler_class(**_lowerCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE: Dict = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE: Optional[Any] = self.dummy_model() __SCREAMING_SNAKE_CASE: Dict = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE: Optional[int] = sample.to(_lowerCAmelCase ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE: Any = scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Union[str, Any] = model(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Optional[Any] = scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: int = output.prev_sample __SCREAMING_SNAKE_CASE: Tuple = torch.sum(torch.abs(_lowerCAmelCase ) ) __SCREAMING_SNAKE_CASE: List[Any] = torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def snake_case_ ( self ): """simple docstring""" __SCREAMING_SNAKE_CASE: Any = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE: Union[str, Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) __SCREAMING_SNAKE_CASE: str = scheduler_class(**_lowerCAmelCase ) scheduler.set_timesteps(self.num_inference_steps ) __SCREAMING_SNAKE_CASE: str = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE: Optional[int] = self.dummy_model() __SCREAMING_SNAKE_CASE: Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma __SCREAMING_SNAKE_CASE: Any = sample.to(_lowerCAmelCase ) for i, t in enumerate(scheduler.timesteps ): __SCREAMING_SNAKE_CASE: Tuple = scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Tuple = model(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Union[str, Any] = scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Optional[int] = output.prev_sample __SCREAMING_SNAKE_CASE: List[Any] = torch.sum(torch.abs(_lowerCAmelCase ) ) __SCREAMING_SNAKE_CASE: Any = torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 0.0002 ) < 1e-2 assert abs(result_mean.item() - 2.26_76e-06 ) < 1e-3 def snake_case_ ( self ): """simple docstring""" __SCREAMING_SNAKE_CASE: Any = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE: Tuple = self.get_scheduler_config() __SCREAMING_SNAKE_CASE: List[str] = scheduler_class(**_lowerCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: List[str] = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE: Optional[Any] = self.dummy_model() __SCREAMING_SNAKE_CASE: int = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __SCREAMING_SNAKE_CASE: Any = sample.to(_lowerCAmelCase ) for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE: Optional[Any] = scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Tuple = model(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Optional[int] = scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: int = output.prev_sample __SCREAMING_SNAKE_CASE: List[str] = torch.sum(torch.abs(_lowerCAmelCase ) ) __SCREAMING_SNAKE_CASE: Dict = torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 10.0807 ) < 1e-2 assert abs(result_mean.item() - 0.0131 ) < 1e-3 def snake_case_ ( self ): """simple docstring""" __SCREAMING_SNAKE_CASE: int = self.scheduler_classes[0] __SCREAMING_SNAKE_CASE: str = self.get_scheduler_config() __SCREAMING_SNAKE_CASE: Union[str, Any] = scheduler_class(**_lowerCAmelCase , use_karras_sigmas=_lowerCAmelCase ) scheduler.set_timesteps(self.num_inference_steps , device=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: int = torch.manual_seed(0 ) __SCREAMING_SNAKE_CASE: Any = self.dummy_model() __SCREAMING_SNAKE_CASE: str = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __SCREAMING_SNAKE_CASE: Optional[int] = sample.to(_lowerCAmelCase ) for t in scheduler.timesteps: __SCREAMING_SNAKE_CASE: Optional[Any] = scheduler.scale_model_input(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: List[Any] = model(_lowerCAmelCase , _lowerCAmelCase ) __SCREAMING_SNAKE_CASE: Any = scheduler.step(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , generator=_lowerCAmelCase ) __SCREAMING_SNAKE_CASE: List[str] = output.prev_sample __SCREAMING_SNAKE_CASE: int = torch.sum(torch.abs(_lowerCAmelCase ) ) __SCREAMING_SNAKE_CASE: Optional[int] = torch.mean(torch.abs(_lowerCAmelCase ) ) assert abs(result_sum.item() - 124.52299499511719 ) < 1e-2 assert abs(result_mean.item() - 0.16213932633399963 ) < 1e-3
146
0
def UpperCamelCase_( lowerCamelCase_ ) -> list: _lowercase : Optional[Any] = len(lowerCamelCase_ ) for i in range(1 , lowerCamelCase_ ): _lowercase : Tuple = collection[i] _lowercase : str = 0 _lowercase : List[str] = i - 1 while low <= high: _lowercase : int = (low + high) // 2 if val < collection[mid]: _lowercase : Union[str, Any] = mid - 1 else: _lowercase : int = mid + 1 for j in range(lowerCamelCase_ , lowerCamelCase_ , -1 ): _lowercase : Optional[Any] = collection[j - 1] _lowercase : List[str] = val return collection if __name__ == "__main__": SCREAMING_SNAKE_CASE : int = input("Enter numbers separated by a comma:\n").strip() SCREAMING_SNAKE_CASE : int = [int(item) for item in user_input.split(",")] print(binary_insertion_sort(unsorted))
89
from __future__ import annotations import numpy as np def UpperCamelCase_( lowerCamelCase_ ) -> Optional[int]: return np.maximum(0 , lowerCamelCase_ ) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
89
1
class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self : Optional[int] , lowerCamelCase : int , lowerCamelCase : int=None , lowerCamelCase : int=None ) -> Dict: """simple docstring""" _UpperCAmelCase = data _UpperCAmelCase = previous _UpperCAmelCase = next_node def __str__( self : str ) -> str: """simple docstring""" return f"""{self.data}""" def lowerCamelCase ( self : List[Any] ) -> int: """simple docstring""" return self.data def lowerCamelCase ( self : Dict ) -> str: """simple docstring""" return self.next def lowerCamelCase ( self : Dict ) -> Dict: """simple docstring""" return self.previous class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self : List[str] , lowerCamelCase : Union[str, Any] ) -> str: """simple docstring""" _UpperCAmelCase = head def __iter__( self : List[Any] ) -> Dict: """simple docstring""" return self def lowerCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" if not self.current: raise StopIteration else: _UpperCAmelCase = self.current.get_data() _UpperCAmelCase = self.current.get_next() return value class SCREAMING_SNAKE_CASE__ : '''simple docstring''' def __init__( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" _UpperCAmelCase = None # First node in list _UpperCAmelCase = None # Last node in list def __str__( self : Dict ) -> int: """simple docstring""" _UpperCAmelCase = self.head _UpperCAmelCase = [] while current is not None: nodes.append(current.get_data() ) _UpperCAmelCase = current.get_next() return " ".join(str(_UpperCAmelCase ) for node in nodes ) def __contains__( self : str , lowerCamelCase : int ) -> Dict: """simple docstring""" _UpperCAmelCase = self.head while current: if current.get_data() == value: return True _UpperCAmelCase = current.get_next() return False def __iter__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" return LinkedListIterator(self.head ) def lowerCamelCase ( self : str ) -> str: """simple docstring""" if self.head: return self.head.get_data() return None def lowerCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if self.tail: return self.tail.get_data() return None def lowerCamelCase ( self : Union[str, Any] , lowerCamelCase : Node ) -> None: """simple docstring""" if self.head is None: _UpperCAmelCase = node _UpperCAmelCase = node else: self.insert_before_node(self.head , _UpperCAmelCase ) def lowerCamelCase ( self : List[Any] , lowerCamelCase : Node ) -> None: """simple docstring""" if self.head is None: self.set_head(_UpperCAmelCase ) else: self.insert_after_node(self.tail , _UpperCAmelCase ) def lowerCamelCase ( self : str , lowerCamelCase : int ) -> None: """simple docstring""" _UpperCAmelCase = Node(_UpperCAmelCase ) if self.head is None: self.set_head(_UpperCAmelCase ) else: self.set_tail(_UpperCAmelCase ) def lowerCamelCase ( self : List[Any] , lowerCamelCase : Node , lowerCamelCase : Node ) -> None: """simple docstring""" _UpperCAmelCase = node _UpperCAmelCase = node.previous if node.get_previous() is None: _UpperCAmelCase = node_to_insert else: _UpperCAmelCase = node_to_insert _UpperCAmelCase = node_to_insert def lowerCamelCase ( self : Tuple , lowerCamelCase : Node , lowerCamelCase : Node ) -> None: """simple docstring""" _UpperCAmelCase = node _UpperCAmelCase = node.next if node.get_next() is None: _UpperCAmelCase = node_to_insert else: _UpperCAmelCase = node_to_insert _UpperCAmelCase = node_to_insert def lowerCamelCase ( self : Dict , lowerCamelCase : int , lowerCamelCase : int ) -> None: """simple docstring""" _UpperCAmelCase = 1 _UpperCAmelCase = Node(_UpperCAmelCase ) _UpperCAmelCase = self.head while node: if current_position == position: self.insert_before_node(_UpperCAmelCase , _UpperCAmelCase ) return current_position += 1 _UpperCAmelCase = node.next self.insert_after_node(self.tail , _UpperCAmelCase ) def lowerCamelCase ( self : Tuple , lowerCamelCase : int ) -> Node: """simple docstring""" _UpperCAmelCase = self.head while node: if node.get_data() == item: return node _UpperCAmelCase = node.get_next() raise Exception("""Node not found""" ) def lowerCamelCase ( self : Optional[Any] , lowerCamelCase : Optional[int] ) -> int: """simple docstring""" if (node := self.get_node(_UpperCAmelCase )) is not None: if node == self.head: _UpperCAmelCase = self.head.get_next() if node == self.tail: _UpperCAmelCase = self.tail.get_previous() self.remove_node_pointers(_UpperCAmelCase ) @staticmethod def lowerCamelCase ( lowerCamelCase : Node ) -> None: """simple docstring""" if node.get_next(): _UpperCAmelCase = node.previous if node.get_previous(): _UpperCAmelCase = node.next _UpperCAmelCase = None _UpperCAmelCase = None def lowerCamelCase ( self : int ) -> Tuple: """simple docstring""" return self.head is None def _SCREAMING_SNAKE_CASE ( ) -> int: pass if __name__ == "__main__": import doctest doctest.testmod()
714
def _SCREAMING_SNAKE_CASE ( __snake_case ) -> float: return 1_0 - x * x def _SCREAMING_SNAKE_CASE ( __snake_case , __snake_case ) -> float: # Bolzano theory in order to find if there is a root between a and b if equation(__snake_case ) * equation(__snake_case ) >= 0: raise ValueError("""Wrong space!""" ) _UpperCAmelCase = a while (b - a) >= 0.01: # Find middle point _UpperCAmelCase = (a + b) / 2 # Check if middle point is root if equation(__snake_case ) == 0.0: break # Decide the side to repeat the steps if equation(__snake_case ) * equation(__snake_case ) < 0: _UpperCAmelCase = c else: _UpperCAmelCase = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
402
0
from __future__ import annotations from collections import deque class lowercase_ : '''simple docstring''' def __init__( self : List[Any] , __UpperCAmelCase : list[str] ) ->Union[str, Any]: """simple docstring""" a = [] self.adlist.append( {'''value''': '''''', '''next_states''': [], '''fail_state''': 0, '''output''': []} ) for keyword in keywords: self.add_keyword(__UpperCAmelCase ) self.set_fail_transitions() def __lowerCAmelCase ( self : List[Any] , __UpperCAmelCase : int , __UpperCAmelCase : str ) ->int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def __lowerCAmelCase ( self : str , __UpperCAmelCase : str ) ->None: """simple docstring""" a = 0 for character in keyword: a = self.find_next_state(__UpperCAmelCase , __UpperCAmelCase ) if next_state is None: self.adlist.append( { '''value''': character, '''next_states''': [], '''fail_state''': 0, '''output''': [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) a = len(self.adlist ) - 1 else: a = next_state self.adlist[current_state]["output"].append(__UpperCAmelCase ) def __lowerCAmelCase ( self : List[Any] ) ->None: """simple docstring""" a = deque() for node in self.adlist[0]["next_states"]: q.append(__UpperCAmelCase ) a = 0 while q: a = q.popleft() for child in self.adlist[r]["next_states"]: q.append(__UpperCAmelCase ) a = self.adlist[r]['''fail_state'''] while ( self.find_next_state(__UpperCAmelCase , self.adlist[child]['''value'''] ) is None and state != 0 ): a = self.adlist[state]['''fail_state'''] a = self.find_next_state( __UpperCAmelCase , self.adlist[child]['''value'''] ) if self.adlist[child]["fail_state"] is None: a = 0 a = ( self.adlist[child]['''output'''] + self.adlist[self.adlist[child]['''fail_state''']]['''output'''] ) def __lowerCAmelCase ( self : Any , __UpperCAmelCase : str ) ->dict[str, list[int]]: """simple docstring""" a = {} # returns a dict with keywords and list of its occurrences a = 0 for i in range(len(__UpperCAmelCase ) ): while ( self.find_next_state(__UpperCAmelCase , string[i] ) is None and current_state != 0 ): a = self.adlist[current_state]['''fail_state'''] a = self.find_next_state(__UpperCAmelCase , string[i] ) if next_state is None: a = 0 else: a = next_state for key in self.adlist[current_state]["output"]: if key not in result: a = [] result[key].append(i - len(__UpperCAmelCase ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
117
# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") class lowercase_ : '''simple docstring''' def __init__( self : Optional[int] , __UpperCAmelCase : str , __UpperCAmelCase : str , __UpperCAmelCase : bool = True , __UpperCAmelCase : bool = False ) ->Tuple: """simple docstring""" a = scheduler a = optimizers if isinstance(__UpperCAmelCase , (list, tuple) ) else [optimizers] a = split_batches a = step_with_optimizer a = GradientState() def __lowerCAmelCase ( self : Tuple , *__UpperCAmelCase : List[Any] , **__UpperCAmelCase : Optional[Any] ) ->int: """simple docstring""" if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step a = AcceleratorState().num_processes for _ in range(__UpperCAmelCase ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) else: self.scheduler.step(*__UpperCAmelCase , **__UpperCAmelCase ) def __lowerCAmelCase ( self : Optional[int] ) ->List[str]: """simple docstring""" return self.scheduler.get_last_lr() def __lowerCAmelCase ( self : Optional[Any] ) ->Any: """simple docstring""" return self.scheduler.state_dict() def __lowerCAmelCase ( self : Union[str, Any] , __UpperCAmelCase : Any ) ->Tuple: """simple docstring""" self.scheduler.load_state_dict(__UpperCAmelCase ) def __lowerCAmelCase ( self : Dict ) ->Optional[int]: """simple docstring""" return self.scheduler.get_lr() def __lowerCAmelCase ( self : int , *__UpperCAmelCase : List[str] , **__UpperCAmelCase : Optional[Any] ) ->List[str]: """simple docstring""" return self.scheduler.print_lr(*__UpperCAmelCase , **__UpperCAmelCase )
117
1
def __lowerCamelCase ( _lowerCAmelCase = 10 , _lowerCAmelCase = 22 ) -> int: _UpperCAmelCase = range(1 , _lowerCAmelCase ) _UpperCAmelCase = range(1 , _lowerCAmelCase ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F'''{solution(1_0, 2_2) = }''')
719
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig __lowerCAmelCase = [ "openmmlab/upernet-convnext-tiny", # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring __lowerCAmelCase = "UperNetConfig" class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : Union[int, Tuple[int, int]] , __UpperCamelCase : Union[int, Tuple[int, int], str] = 0 , __UpperCamelCase : bool = False , __UpperCamelCase : Union[int, Tuple[int, int]] = 1 , ): super().__init__() _UpperCAmelCase = nn.Convad( in_channels=__UpperCamelCase , out_channels=__UpperCamelCase , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , bias=__UpperCamelCase , dilation=__UpperCamelCase , ) _UpperCAmelCase = nn.BatchNormad(__UpperCamelCase ) _UpperCAmelCase = nn.ReLU() def UpperCAmelCase__ ( self : Tuple , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = self.conv(__UpperCamelCase ) _UpperCAmelCase = self.batch_norm(__UpperCamelCase ) _UpperCAmelCase = self.activation(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : str , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : int ): super().__init__() _UpperCAmelCase = [ nn.AdaptiveAvgPoolad(__UpperCamelCase ), UperNetConvModule(__UpperCamelCase , __UpperCamelCase , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(__UpperCamelCase ) , __UpperCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = input for layer in self.layers: _UpperCAmelCase = layer(__UpperCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : Tuple[int, ...] , __UpperCamelCase : int , __UpperCamelCase : int , __UpperCamelCase : bool ): super().__init__() _UpperCAmelCase = pool_scales _UpperCAmelCase = align_corners _UpperCAmelCase = in_channels _UpperCAmelCase = channels _UpperCAmelCase = [] for i, pool_scale in enumerate(__UpperCamelCase ): _UpperCAmelCase = UperNetPyramidPoolingBlock(pool_scale=__UpperCamelCase , in_channels=__UpperCamelCase , channels=__UpperCamelCase ) self.blocks.append(__UpperCamelCase ) self.add_module(str(__UpperCamelCase ) , __UpperCamelCase ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): _UpperCAmelCase = [] for ppm in self.blocks: _UpperCAmelCase = ppm(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate( __UpperCamelCase , size=x.size()[2:] , mode="bilinear" , align_corners=self.align_corners ) ppm_outs.append(__UpperCamelCase ) return ppm_outs class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Tuple , __UpperCamelCase : int , __UpperCamelCase : Tuple ): super().__init__() _UpperCAmelCase = config _UpperCAmelCase = config.pool_scales # e.g. (1, 2, 3, 6) _UpperCAmelCase = in_channels _UpperCAmelCase = config.hidden_size _UpperCAmelCase = False _UpperCAmelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module _UpperCAmelCase = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) _UpperCAmelCase = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module _UpperCAmelCase = nn.ModuleList() _UpperCAmelCase = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer _UpperCAmelCase = UperNetConvModule(__UpperCamelCase , self.channels , kernel_size=1 ) _UpperCAmelCase = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(__UpperCamelCase ) self.fpn_convs.append(__UpperCamelCase ) _UpperCAmelCase = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def UpperCAmelCase__ ( self : str ): self.apply(self._init_weights ) def UpperCAmelCase__ ( self : Optional[int] , __UpperCamelCase : str ): if isinstance(__UpperCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Union[str, Any] ): _UpperCAmelCase = inputs[-1] _UpperCAmelCase = [x] psp_outs.extend(self.psp_modules(__UpperCamelCase ) ) _UpperCAmelCase = torch.cat(__UpperCamelCase , dim=1 ) _UpperCAmelCase = self.bottleneck(__UpperCamelCase ) return output def UpperCAmelCase__ ( self : Any , __UpperCamelCase : torch.Tensor ): # build laterals _UpperCAmelCase = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(__UpperCamelCase ) ) # build top-down path _UpperCAmelCase = len(__UpperCamelCase ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _UpperCAmelCase = laterals[i - 1].shape[2:] _UpperCAmelCase = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=__UpperCamelCase , mode="bilinear" , align_corners=self.align_corners ) # build outputs _UpperCAmelCase = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): _UpperCAmelCase = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode="bilinear" , align_corners=self.align_corners ) _UpperCAmelCase = torch.cat(__UpperCamelCase , dim=1 ) _UpperCAmelCase = self.fpn_bottleneck(__UpperCamelCase ) _UpperCAmelCase = self.classifier(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( nn.Module): def __init__( self : Dict , __UpperCamelCase : str , __UpperCamelCase : int = 2 , __UpperCamelCase : int = 3 , __UpperCamelCase : Union[int, Tuple[int, int]] = 1 ): super().__init__() _UpperCAmelCase = config _UpperCAmelCase = config.auxiliary_in_channels _UpperCAmelCase = config.auxiliary_channels _UpperCAmelCase = config.auxiliary_num_convs _UpperCAmelCase = config.auxiliary_concat_input _UpperCAmelCase = in_index _UpperCAmelCase = (kernel_size // 2) * dilation _UpperCAmelCase = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , dilation=__UpperCamelCase ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=__UpperCamelCase , padding=__UpperCamelCase , dilation=__UpperCamelCase ) ) if self.num_convs == 0: _UpperCAmelCase = nn.Identity() else: _UpperCAmelCase = nn.Sequential(*__UpperCamelCase ) if self.concat_input: _UpperCAmelCase = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=__UpperCamelCase , padding=kernel_size // 2 ) _UpperCAmelCase = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def UpperCAmelCase__ ( self : List[Any] ): self.apply(self._init_weights ) def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : Optional[Any] ): if isinstance(__UpperCamelCase , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def UpperCAmelCase__ ( self : Union[str, Any] , __UpperCamelCase : torch.Tensor ): # just take the relevant feature maps _UpperCAmelCase = encoder_hidden_states[self.in_index] _UpperCAmelCase = self.convs(__UpperCamelCase ) if self.concat_input: _UpperCAmelCase = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) _UpperCAmelCase = self.classifier(__UpperCamelCase ) return output class __SCREAMING_SNAKE_CASE ( lowercase): __SCREAMING_SNAKE_CASE : Dict = UperNetConfig __SCREAMING_SNAKE_CASE : str = """pixel_values""" __SCREAMING_SNAKE_CASE : str = True def UpperCAmelCase__ ( self : Tuple , __UpperCamelCase : int ): if isinstance(__UpperCamelCase , __UpperCamelCase ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def UpperCAmelCase__ ( self : Union[str, Any] ): self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Tuple , __UpperCamelCase : Tuple=False ): if isinstance(__UpperCamelCase , __UpperCamelCase ): _UpperCAmelCase = value __lowerCAmelCase = r"\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" __lowerCAmelCase = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( """UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.""" , lowercase , ) class __SCREAMING_SNAKE_CASE ( lowercase): def __init__( self : Optional[int] , __UpperCamelCase : str ): super().__init__(__UpperCamelCase ) _UpperCAmelCase = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) _UpperCAmelCase = UperNetHead(__UpperCamelCase , in_channels=self.backbone.channels ) _UpperCAmelCase = UperNetFCNHead(__UpperCamelCase ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format("batch_size, sequence_length" ) ) @replace_return_docstrings(output_type=__UpperCamelCase , config_class=_CONFIG_FOR_DOC ) def UpperCAmelCase__ ( self : Dict , __UpperCamelCase : Optional[torch.Tensor] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : Optional[bool] = None , __UpperCamelCase : Optional[torch.Tensor] = None , __UpperCamelCase : Optional[bool] = None , ): _UpperCAmelCase = return_dict if return_dict is not None else self.config.use_return_dict _UpperCAmelCase = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _UpperCAmelCase = output_attentions if output_attentions is not None else self.config.output_attentions _UpperCAmelCase = self.backbone.forward_with_filtered_kwargs( __UpperCamelCase , output_hidden_states=__UpperCamelCase , output_attentions=__UpperCamelCase ) _UpperCAmelCase = outputs.feature_maps _UpperCAmelCase = self.decode_head(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate(__UpperCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=__UpperCamelCase ) _UpperCAmelCase = None if self.auxiliary_head is not None: _UpperCAmelCase = self.auxiliary_head(__UpperCamelCase ) _UpperCAmelCase = nn.functional.interpolate( __UpperCamelCase , size=pixel_values.shape[2:] , mode="bilinear" , align_corners=__UpperCamelCase ) _UpperCAmelCase = None if labels is not None: if self.config.num_labels == 1: raise ValueError("The number of labels should be greater than one" ) else: # compute weighted loss _UpperCAmelCase = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) _UpperCAmelCase = loss_fct(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = loss_fct(__UpperCamelCase , __UpperCamelCase ) _UpperCAmelCase = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: _UpperCAmelCase = (logits,) + outputs[1:] else: _UpperCAmelCase = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=__UpperCamelCase , logits=__UpperCamelCase , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
129
0
import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() _lowerCamelCase = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: Dict ): SCREAMING_SNAKE_CASE__ = WavaVecaForSequenceClassification.from_pretrained(UpperCamelCase__ , config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = downstream_dict["""projector.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""projector.bias"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.post_net.linear.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.post_net.linear.bias"""] return model def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Dict , UpperCamelCase__: Dict , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = WavaVecaForAudioFrameClassification.from_pretrained(UpperCamelCase__ , config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = downstream_dict["""model.linear.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.linear.bias"""] return model def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: List[str] , UpperCamelCase__: Any ): SCREAMING_SNAKE_CASE__ = WavaVecaForXVector.from_pretrained(UpperCamelCase__ , config=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = downstream_dict["""connector.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""connector.bias"""] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE__ = downstream_dict[ f'''model.framelevel_feature_extractor.module.{i}.kernel.weight''' ] SCREAMING_SNAKE_CASE__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias'''] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""] SCREAMING_SNAKE_CASE__ = downstream_dict["""objective.W"""] return model @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( UpperCamelCase__: Any , UpperCamelCase__: Tuple , UpperCamelCase__: Optional[Any] , UpperCamelCase__: Union[str, Any] ): SCREAMING_SNAKE_CASE__ = torch.load(UpperCamelCase__ , map_location="""cpu""" ) SCREAMING_SNAKE_CASE__ = checkpoint["""Downstream"""] SCREAMING_SNAKE_CASE__ = WavaVecaConfig.from_pretrained(UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = WavaVecaFeatureExtractor.from_pretrained( UpperCamelCase__ , return_attention_mask=UpperCamelCase__ , do_normalize=UpperCamelCase__ ) SCREAMING_SNAKE_CASE__ = hf_config.architectures[0] if arch.endswith("""ForSequenceClassification""" ): SCREAMING_SNAKE_CASE__ = convert_classification(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) elif arch.endswith("""ForAudioFrameClassification""" ): SCREAMING_SNAKE_CASE__ = convert_diarization(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) elif arch.endswith("""ForXVector""" ): SCREAMING_SNAKE_CASE__ = convert_xvector(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE__ = checkpoint["""Featurizer"""]["""weights"""] hf_feature_extractor.save_pretrained(UpperCamelCase__ ) hf_model.save_pretrained(UpperCamelCase__ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() parser.add_argument( '--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.' ) parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.') parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.') _lowerCamelCase = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
6
from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { "shi-labs/dinat-mini-in1k-224": "https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json", # See all Dinat models at https://huggingface.co/models?filter=dinat } class lowerCAmelCase_ ( lowercase , lowercase ): """simple docstring""" _snake_case : Tuple = """dinat""" _snake_case : List[Any] = { """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers""", } def __init__( self :Optional[int] , lowerCamelCase__ :int=4 , lowerCamelCase__ :Union[str, Any]=3 , lowerCamelCase__ :List[Any]=64 , lowerCamelCase__ :Any=[3, 4, 6, 5] , lowerCamelCase__ :Tuple=[2, 4, 8, 16] , lowerCamelCase__ :Optional[int]=7 , lowerCamelCase__ :Tuple=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , lowerCamelCase__ :Tuple=3.0 , lowerCamelCase__ :str=True , lowerCamelCase__ :Optional[int]=0.0 , lowerCamelCase__ :Optional[Any]=0.0 , lowerCamelCase__ :int=0.1 , lowerCamelCase__ :Optional[Any]="gelu" , lowerCamelCase__ :Optional[Any]=0.02 , lowerCamelCase__ :Union[str, Any]=1e-5 , lowerCamelCase__ :Optional[int]=0.0 , lowerCamelCase__ :List[str]=None , lowerCamelCase__ :str=None , **lowerCamelCase__ :List[Any] , ): super().__init__(**lowerCamelCase__ ) UpperCamelCase__ :Any = patch_size UpperCamelCase__ :Any = num_channels UpperCamelCase__ :int = embed_dim UpperCamelCase__ :Optional[Any] = depths UpperCamelCase__ :Any = len(lowerCamelCase__ ) UpperCamelCase__ :str = num_heads UpperCamelCase__ :Optional[int] = kernel_size UpperCamelCase__ :Optional[int] = dilations UpperCamelCase__ :Tuple = mlp_ratio UpperCamelCase__ :Dict = qkv_bias UpperCamelCase__ :List[str] = hidden_dropout_prob UpperCamelCase__ :List[str] = attention_probs_dropout_prob UpperCamelCase__ :Union[str, Any] = drop_path_rate UpperCamelCase__ :Tuple = hidden_act UpperCamelCase__ :List[Any] = layer_norm_eps UpperCamelCase__ :Optional[Any] = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model UpperCamelCase__ :Tuple = int(embed_dim * 2 ** (len(lowerCamelCase__ ) - 1) ) UpperCamelCase__ :Tuple = layer_scale_init_value UpperCamelCase__ :Optional[int] = ["""stem"""] + [f"""stage{idx}""" for idx in range(1 , len(lowerCamelCase__ ) + 1 )] UpperCamelCase__ , UpperCamelCase__ :List[str] = get_aligned_output_features_output_indices( out_features=lowerCamelCase__ , out_indices=lowerCamelCase__ , stage_names=self.stage_names )
45
0
"""simple docstring""" import socket def a__ ( ) -> int: lowerCamelCase = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) lowerCamelCase = socket.gethostname() lowerCamelCase = 1_23_12 sock.connect((host, port) ) sock.send(b"""Hello server!""" ) with open("""Received_file""" , """wb""" ) as out_file: print("""File opened""" ) print("""Receiving data...""" ) while True: lowerCamelCase = sock.recv(10_24 ) if not data: break out_file.write(snake_case__ ) print("""Successfully received the file""" ) sock.close() print("""Connection closed""" ) if __name__ == "__main__": main()
533
"""simple docstring""" import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss lowerCAmelCase : List[Any] = pytest.mark.integration @require_faiss class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = Dataset.from_dict({"""filename""": ["""my_name-train""" + """_""" + str(_a ) for x in np.arange(30 ).tolist()]} ) return dset def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = self._create_dummy_dataset() lowerCamelCase = dset.map( lambda _a , _a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=_a , keep_in_memory=_a ) lowerCamelCase = dset.add_faiss_index("""vecs""" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT ) lowerCamelCase , lowerCamelCase = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) dset.drop_index("""vecs""" ) def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , batch_size=100 , metric_type=faiss.METRIC_INNER_PRODUCT , ) lowerCamelCase , lowerCamelCase = dset.get_nearest_examples("""vecs""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: dset.save_faiss_index("""vecs""" , tmp_file.name ) dset.load_faiss_index("""vecs2""" , tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase , lowerCamelCase = dset.get_nearest_examples("""vecs2""" , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 , 1 ) , index_name="""vecs""" ) dset.drop_index("""vecs""" ) self.assertRaises(_a , partial(dset.get_nearest_examples , """vecs2""" , np.ones(5 , dtype=np.floataa ) ) ) def _lowerCAmelCase ( self ): """simple docstring""" from elasticsearch import Elasticsearch lowerCamelCase = self._create_dummy_dataset() with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: lowerCamelCase = {"""acknowledged""": True} mocked_bulk.return_value([(True, None)] * 30 ) lowerCamelCase = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 29}]}} lowerCamelCase = Elasticsearch() dset.add_elasticsearch_index("""filename""" , es_client=_a ) lowerCamelCase , lowerCamelCase = dset.get_nearest_examples("""filename""" , """my_name-train_29""" ) self.assertEqual(examples["""filename"""][0] , """my_name-train_29""" ) @require_faiss class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 10 ) # single query lowerCamelCase = np.zeros(5 , dtype=np.floataa ) lowerCamelCase = 1 lowerCamelCase , lowerCamelCase = index.search(_a ) self.assertRaises(_a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries lowerCamelCase = np.eye(5 , dtype=np.floataa )[::-1] lowerCamelCase , lowerCamelCase = index.search_batch(_a ) self.assertRaises(_a , index.search_batch , queries[0] ) lowerCamelCase = [scores[0] for scores in total_scores] lowerCamelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , _a ) def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = FaissIndex(string_factory="""Flat""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) lowerCamelCase = FaissIndex(string_factory="""LSH""" ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(_a ): lowerCamelCase = FaissIndex(string_factory="""Flat""" , custom_index=faiss.IndexFlat(5 ) ) def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = faiss.IndexFlat(5 ) lowerCamelCase = FaissIndex(custom_index=_a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def _lowerCAmelCase ( self ): """simple docstring""" import faiss lowerCamelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: index.save(tmp_file.name ) lowerCamelCase = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) lowerCamelCase = np.zeros(5 , dtype=np.floataa ) lowerCamelCase = 1 lowerCamelCase , lowerCamelCase = index.search(_a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def a__ ( snake_case__ ) -> Tuple: import faiss lowerCamelCase = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) lowerCamelCase = """index.faiss""" lowerCamelCase = F'mock://{index_name}' index.save(snake_case__ , storage_options=mockfs.storage_options ) lowerCamelCase = FaissIndex.load(snake_case__ , storage_options=mockfs.storage_options ) lowerCamelCase = np.zeros(5 , dtype=np.floataa ) lowerCamelCase = 1 lowerCamelCase , lowerCamelCase = index.search(snake_case__ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class __magic_name__ ( UpperCAmelCase__ ): '''simple docstring''' def _lowerCAmelCase ( self ): """simple docstring""" from elasticsearch import Elasticsearch with patch("""elasticsearch.Elasticsearch.search""" ) as mocked_search, patch( """elasticsearch.client.IndicesClient.create""" ) as mocked_index_create, patch("""elasticsearch.helpers.streaming_bulk""" ) as mocked_bulk: lowerCamelCase = Elasticsearch() lowerCamelCase = {"""acknowledged""": True} lowerCamelCase = ElasticSearchIndex(es_client=_a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["""foo""", """bar""", """foobar"""] ) # single query lowerCamelCase = """foo""" lowerCamelCase = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}} lowerCamelCase , lowerCamelCase = index.search(_a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout lowerCamelCase = """foo""" lowerCamelCase = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 0}]}} lowerCamelCase , lowerCamelCase = index.search(_a , request_timeout=30 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries lowerCamelCase = ["""foo""", """bar""", """foobar"""] lowerCamelCase = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}} lowerCamelCase , lowerCamelCase = index.search_batch(_a ) lowerCamelCase = [scores[0] for scores in total_scores] lowerCamelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a ) # batched queries with timeout lowerCamelCase = ["""foo""", """bar""", """foobar"""] lowerCamelCase = {"""hits""": {"""hits""": [{"""_score""": 1, """_id""": 1}]}} lowerCamelCase , lowerCamelCase = index.search_batch(_a , request_timeout=30 ) lowerCamelCase = [scores[0] for scores in total_scores] lowerCamelCase = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a )
533
1
'''simple docstring''' import argparse import hashlib # hashlib is only used inside the Test class import struct class A : def __init__( self , SCREAMING_SNAKE_CASE ) -> Dict: """simple docstring""" A : Optional[int] = data A : Optional[int] = [0X67_452_301, 0XEF_CDA_B89, 0X98_BAD_CFE, 0X10_325_476, 0XC3_D2E_1F0] @staticmethod def __lowerCAmelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: """simple docstring""" return ((n << b) | (n >> (32 - b))) & 0XFF_FFF_FFF def __lowerCAmelCase ( self ) -> Optional[Any]: """simple docstring""" A : Optional[int] = b'''\x80''' + b'''\x00''' * (63 - (len(self.data ) + 8) % 64) A : Optional[int] = self.data + padding + struct.pack('''>Q''' , 8 * len(self.data ) ) return padded_data def __lowerCAmelCase ( self ) -> Any: """simple docstring""" return [ self.padded_data[i : i + 64] for i in range(0 , len(self.padded_data ) , 64 ) ] def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[Any]: """simple docstring""" A : int = list(struct.unpack('''>16L''' , SCREAMING_SNAKE_CASE ) ) + [0] * 64 for i in range(16 , 80 ): A : Optional[int] = self.rotate((w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]) , 1 ) return w def __lowerCAmelCase ( self ) -> Dict: """simple docstring""" A : Optional[int] = self.padding() A : List[Any] = self.split_blocks() for block in self.blocks: A : Optional[int] = self.expand_block(SCREAMING_SNAKE_CASE ) A, A, A, A, A : Union[str, Any] = self.h for i in range(0 , 80 ): if 0 <= i < 20: A : Optional[Any] = (b & c) | ((~b) & d) A : Dict = 0X5A_827_999 elif 20 <= i < 40: A : Union[str, Any] = b ^ c ^ d A : Optional[int] = 0X6E_D9E_BA1 elif 40 <= i < 60: A : Union[str, Any] = (b & c) | (b & d) | (c & d) A : int = 0X8F_1BB_CDC elif 60 <= i < 80: A : str = b ^ c ^ d A : Optional[int] = 0XCA_62C_1D6 A, A, A, A, A : Tuple = ( self.rotate(SCREAMING_SNAKE_CASE , 5 ) + f + e + k + expanded_block[i] & 0XFF_FFF_FFF, a, self.rotate(SCREAMING_SNAKE_CASE , 30 ), c, d, ) A : Optional[Any] = ( self.h[0] + a & 0XFF_FFF_FFF, self.h[1] + b & 0XFF_FFF_FFF, self.h[2] + c & 0XFF_FFF_FFF, self.h[3] + d & 0XFF_FFF_FFF, self.h[4] + e & 0XFF_FFF_FFF, ) return ("{:08x}" * 5).format(*self.h ) def lowerCAmelCase_ ( ): '''simple docstring''' A : str = B'''Test String''' assert SHAaHash(snake_case__ ).final_hash() == hashlib.shaa(snake_case__ ).hexdigest() # noqa: S324 def lowerCAmelCase_ ( ): '''simple docstring''' A : Optional[Any] = argparse.ArgumentParser(description='''Process some strings or files''' ) parser.add_argument( '''--string''' , dest='''input_string''' , default='''Hello World!! Welcome to Cryptography''' , help='''Hash the string''' , ) parser.add_argument('''--file''' , dest='''input_file''' , help='''Hash contents of a file''' ) A : Any = parser.parse_args() A : Dict = args.input_string # In any case hash input should be a bytestring if args.input_file: with open(args.input_file , '''rb''' ) as f: A : Optional[Any] = f.read() else: A : List[Any] = bytes(snake_case__ , '''utf-8''' ) print(SHAaHash(snake_case__ ).final_hash() ) if __name__ == "__main__": main() import doctest doctest.testmod()
634
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : int = { 'ut/deta': 'https://huggingface.co/ut/deta/resolve/main/config.json', } class A ( __snake_case ): __magic_name__ = '''deta''' __magic_name__ = { '''hidden_size''': '''d_model''', '''num_attention_heads''': '''encoder_attention_heads''', } def __init__( self , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=900 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=6 , SCREAMING_SNAKE_CASE=2048 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=6 , SCREAMING_SNAKE_CASE=1024 , SCREAMING_SNAKE_CASE=8 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE="relu" , SCREAMING_SNAKE_CASE=256 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=1.0 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE="sine" , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=300 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=1 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=0.25 , **SCREAMING_SNAKE_CASE , ) -> Any: """simple docstring""" if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) A : Optional[Any] = CONFIG_MAPPING['''resnet'''](out_features=['''stage2''', '''stage3''', '''stage4'''] ) else: if isinstance(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): A : List[Any] = backbone_config.pop('''model_type''' ) A : List[Any] = CONFIG_MAPPING[backbone_model_type] A : Optional[int] = config_class.from_dict(SCREAMING_SNAKE_CASE ) A : str = backbone_config A : Optional[int] = num_queries A : Dict = max_position_embeddings A : Optional[Any] = d_model A : Optional[Any] = encoder_ffn_dim A : List[str] = encoder_layers A : Tuple = encoder_attention_heads A : Optional[Any] = decoder_ffn_dim A : Optional[int] = decoder_layers A : List[str] = decoder_attention_heads A : Union[str, Any] = dropout A : str = attention_dropout A : Any = activation_dropout A : Optional[int] = activation_function A : Tuple = init_std A : Any = init_xavier_std A : Optional[Any] = encoder_layerdrop A : int = auxiliary_loss A : Dict = position_embedding_type # deformable attributes A : str = num_feature_levels A : Optional[int] = encoder_n_points A : Any = decoder_n_points A : Tuple = two_stage A : Dict = two_stage_num_proposals A : List[str] = with_box_refine A : List[str] = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher A : Dict = class_cost A : Optional[int] = bbox_cost A : Optional[Any] = giou_cost # Loss coefficients A : int = mask_loss_coefficient A : int = dice_loss_coefficient A : Tuple = bbox_loss_coefficient A : int = giou_loss_coefficient A : Dict = eos_coefficient A : Optional[Any] = focal_alpha super().__init__(is_encoder_decoder=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def __lowerCAmelCase ( self ) -> int: """simple docstring""" return self.encoder_attention_heads @property def __lowerCAmelCase ( self ) -> int: """simple docstring""" return self.d_model def __lowerCAmelCase ( self ) -> Any: """simple docstring""" A : Any = copy.deepcopy(self.__dict__ ) A : Dict = self.backbone_config.to_dict() A : List[Any] = self.__class__.model_type return output
634
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_segformer import SegformerImageProcessor UpperCamelCase__ : Optional[int] = logging.get_logger(__name__) class _UpperCamelCase ( lowerCamelCase__ ): '''simple docstring''' def __init__( self : Tuple , *lowerCAmelCase__ : str , **lowerCAmelCase__ : Tuple ): """simple docstring""" warnings.warn( """The class SegformerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use SegformerImageProcessor instead.""" , lowerCAmelCase__ , ) super().__init__(*lowerCAmelCase__ , **lowerCAmelCase__ )
178
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCamelCase__ : List[Any] = { '''configuration_time_series_transformer''': [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimeSeriesTransformerConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase__ : List[Any] = [ '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimeSeriesTransformerForPrediction''', '''TimeSeriesTransformerModel''', '''TimeSeriesTransformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys UpperCamelCase__ : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
178
1
"""simple docstring""" import json import logging import os import sys from time import time from unittest.mock import patch from transformers.testing_utils import TestCasePlus, require_torch_tpu logging.basicConfig(level=logging.DEBUG) _lowerCAmelCase :str = logging.getLogger() def lowerCamelCase_ (UpperCamelCase__ : Tuple ): _UpperCAmelCase : List[Any] = {} _UpperCAmelCase : Optional[int] = os.path.join(UpperCamelCase__ , '''all_results.json''' ) if os.path.exists(UpperCamelCase__ ): with open(UpperCamelCase__ , '''r''' ) as f: _UpperCAmelCase : Any = json.load(UpperCamelCase__ ) else: raise ValueError(F'can\'t find {path}' ) return results _lowerCAmelCase :List[Any] = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) @require_torch_tpu class _UpperCAmelCase ( lowerCAmelCase_ ): '''simple docstring''' def __lowerCAmelCase ( self ) -> Union[str, Any]: import xla_spawn _UpperCAmelCase : Dict = self.get_auto_remove_tmp_dir() _UpperCAmelCase : List[str] = f'\n ./examples/pytorch/text-classification/run_glue.py\n --num_cores=8\n ./examples/pytorch/text-classification/run_glue.py\n --model_name_or_path distilbert-base-uncased\n --output_dir {tmp_dir}\n --overwrite_output_dir\n --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n --do_train\n --do_eval\n --debug tpu_metrics_debug\n --per_device_train_batch_size=2\n --per_device_eval_batch_size=1\n --learning_rate=1e-4\n --max_steps=10\n --warmup_steps=2\n --seed=42\n --max_seq_length=128\n '.split() with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): _UpperCAmelCase : Optional[Any] = time() xla_spawn.main() _UpperCAmelCase : int = time() _UpperCAmelCase : Optional[Any] = get_results(SCREAMING_SNAKE_CASE__ ) self.assertGreaterEqual(result['''eval_accuracy'''] , 0.75 ) # Assert that the script takes less than 500 seconds to make sure it doesn't hang. self.assertLess(end - start , 5_0_0 ) def __lowerCAmelCase ( self ) -> Optional[Any]: import xla_spawn _UpperCAmelCase : Any = '\n ./tests/test_trainer_tpu.py\n --num_cores=8\n ./tests/test_trainer_tpu.py\n '.split() with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): xla_spawn.main()
506
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path _lowercase : str =( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) _lowercase : list[int] =[ord(letter) for letter in string.ascii_lowercase] _lowercase : set[int] ={ord(char) for char in VALID_CHARS} _lowercase : list[str] =["the", "be", "to", "of", "and", "in", "that", "have"] def A__ ( lowercase: list[int], lowercase: tuple[int, ...] ) -> str | None: A : str ="" A : int A : int A : int for keychar, cipherchar in zip(cycle(lowercase ), lowercase ): A : Tuple =cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase ) return decoded def A__ ( lowercase: list[int] ) -> list[str]: A : list[str] =[] for key in product(lowercase, repeat=3 ): A : Any =try_key(lowercase, lowercase ) if encoded is not None: possibles.append(lowercase ) return possibles def A__ ( lowercase: list[str], lowercase: str ) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def A__ ( lowercase: str = "p059_cipher.txt" ) -> int: A : list[int] A : list[str] A : str A : str A : str =Path(lowercase ).parent.joinpath(lowercase ).read_text(encoding='utf-8' ) A : Tuple =[int(lowercase ) for number in data.strip().split(',' )] A : Dict =filter_valid_chars(lowercase ) for common_word in COMMON_WORDS: A : List[Any] =filter_common_word(lowercase, lowercase ) if len(lowercase ) == 1: break A : str =possibles[0] return sum(ord(lowercase ) for char in decoded_text ) if __name__ == "__main__": print(f'''{solution() = }''')
305
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowerCAmelCase ={ "configuration_distilbert": [ "DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DistilBertConfig", "DistilBertOnnxConfig", ], "tokenization_distilbert": ["DistilBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =["DistilBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "DistilBertForMaskedLM", "DistilBertForMultipleChoice", "DistilBertForQuestionAnswering", "DistilBertForSequenceClassification", "DistilBertForTokenClassification", "DistilBertModel", "DistilBertPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFDistilBertForMaskedLM", "TFDistilBertForMultipleChoice", "TFDistilBertForQuestionAnswering", "TFDistilBertForSequenceClassification", "TFDistilBertForTokenClassification", "TFDistilBertMainLayer", "TFDistilBertModel", "TFDistilBertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase =[ "FlaxDistilBertForMaskedLM", "FlaxDistilBertForMultipleChoice", "FlaxDistilBertForQuestionAnswering", "FlaxDistilBertForSequenceClassification", "FlaxDistilBertForTokenClassification", "FlaxDistilBertModel", "FlaxDistilBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys __lowerCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
721
import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class __magic_name__ ( unittest.TestCase): def __init__( self : Dict ,__SCREAMING_SNAKE_CASE : Optional[Any] ,__SCREAMING_SNAKE_CASE : Dict=7 ,__SCREAMING_SNAKE_CASE : Optional[int]=3 ,__SCREAMING_SNAKE_CASE : str=1_8 ,__SCREAMING_SNAKE_CASE : Tuple=3_0 ,__SCREAMING_SNAKE_CASE : Dict=4_0_0 ,__SCREAMING_SNAKE_CASE : str=True ,__SCREAMING_SNAKE_CASE : Optional[Any]=None ,__SCREAMING_SNAKE_CASE : int=True ,__SCREAMING_SNAKE_CASE : Union[str, Any]=False ,__SCREAMING_SNAKE_CASE : Optional[int]=True ,__SCREAMING_SNAKE_CASE : Union[str, Any]=True ,__SCREAMING_SNAKE_CASE : Dict=[0.5, 0.5, 0.5] ,__SCREAMING_SNAKE_CASE : Tuple=[0.5, 0.5, 0.5] ,): UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = size if size is not None else {"height": 1_8, "width": 2_0} UpperCAmelCase = do_thumbnail UpperCAmelCase = do_align_axis UpperCAmelCase = do_pad UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std def _UpperCAmelCase ( self : Any ): return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class __magic_name__ ( _a , unittest.TestCase): _UpperCAmelCase : Any = DonutImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self : Optional[int] ): UpperCAmelCase = DonutImageProcessingTester(self ) @property def _UpperCAmelCase ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self : Union[str, Any] ): UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_resize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"size" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_thumbnail" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_align_long_axis" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_pad" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"do_normalize" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_mean" ) ) self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE ,"image_std" ) ) def _UpperCAmelCase ( self : Tuple ): UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size ,{"height": 1_8, "width": 2_0} ) UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ,size=4_2 ) self.assertEqual(image_processor.size ,{"height": 4_2, "width": 4_2} ) # Previous config had dimensions in (width, height) order UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ,size=(4_2, 8_4) ) self.assertEqual(image_processor.size ,{"height": 8_4, "width": 4_2} ) def _UpperCAmelCase ( self : List[str] ): pass @is_flaky() def _UpperCAmelCase ( self : Optional[int] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,Image.Image ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,) # Test batched UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,) @is_flaky() def _UpperCAmelCase ( self : Union[str, Any] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__SCREAMING_SNAKE_CASE ,numpify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,np.ndarray ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,) # Test batched UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,) @is_flaky() def _UpperCAmelCase ( self : Optional[Any] ): # Initialize image_processing UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester ,equal_resolution=__SCREAMING_SNAKE_CASE ,torchify=__SCREAMING_SNAKE_CASE ) for image in image_inputs: self.assertIsInstance(__SCREAMING_SNAKE_CASE ,torch.Tensor ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,) # Test batched UpperCAmelCase = image_processing(__SCREAMING_SNAKE_CASE ,return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape ,( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) ,)
405
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : str ) -> str: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCamelCase__ ( self : List[Any] ) -> Optional[int]: torch.manual_seed(0 ) __magic_name__: Dict = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return model @property def lowerCamelCase__ ( self : List[str] ) -> Optional[int]: torch.manual_seed(0 ) __magic_name__: Tuple = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""") , cross_attention_dim=1_0 , ) return model @property def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: torch.manual_seed(0 ) __magic_name__: Any = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""") , up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""") , ) __magic_name__: Union[str, Any] = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=("""AttnDownBlock2D""", """DownBlock2D""") , up_block_types=("""UpBlock2D""", """AttnUpBlock2D""") , ) return vqvae, unet @slow def lowerCamelCase__ ( self : int ) -> Union[str, Any]: __magic_name__: Tuple = """cpu""" # ensure determinism for the device-dependent torch.Generator __magic_name__: Dict = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __magic_name__: Optional[int] = DDPMScheduler() __magic_name__: str = AudioDiffusionPipeline(vqvae=__snake_case , unet=self.dummy_unet , mel=__snake_case , scheduler=__snake_case ) __magic_name__: Any = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__: Optional[Any] = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: Any = pipe(generator=__snake_case , steps=4 ) __magic_name__: Any = output.audios[0] __magic_name__: List[str] = output.images[0] __magic_name__: int = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: List[str] = pipe(generator=__snake_case , steps=4 , return_dict=__snake_case ) __magic_name__: Optional[int] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __magic_name__: Tuple = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: List[str] = np.frombuffer(image_from_tuple.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: str = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __magic_name__: Optional[Any] = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __magic_name__: Optional[Any] = DDIMScheduler() __magic_name__: Optional[Any] = self.dummy_vqvae_and_unet __magic_name__: int = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__snake_case , scheduler=__snake_case ) __magic_name__: str = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) __magic_name__: Any = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __magic_name__: Any = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: Optional[Any] = pipe(raw_audio=__snake_case , generator=__snake_case , start_step=5 , steps=1_0 ) __magic_name__: List[str] = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __magic_name__: str = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Optional[Any] = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __magic_name__: int = self.dummy_unet_condition __magic_name__: List[Any] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__snake_case , mel=__snake_case , scheduler=__snake_case ) __magic_name__: List[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) __magic_name__: Tuple = torch.rand((1, 1, 1_0) ) __magic_name__: Tuple = pipe(generator=__snake_case , encoding=__snake_case ) __magic_name__: int = output.images[0] __magic_name__: List[Any] = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Optional[int] = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __A ( unittest.TestCase ): def lowerCamelCase__ ( self : Any ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : Union[str, Any] ) -> List[str]: __magic_name__: Dict = torch_device __magic_name__: Dict = DiffusionPipeline.from_pretrained("""teticio/audio-diffusion-ddim-256""" ) __magic_name__: List[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) __magic_name__: Dict = torch.Generator(device=__snake_case ).manual_seed(4_2 ) __magic_name__: str = pipe(generator=__snake_case ) __magic_name__: str = output.audios[0] __magic_name__: Any = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __magic_name__: List[str] = np.frombuffer(image.tobytes() , dtype="""uint8""" )[:1_0] __magic_name__: Any = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
96
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def __lowercase (_lowercase, _lowercase, _lowercase, _lowercase, _lowercase, _lowercase ) -> np.ndarray: """simple docstring""" # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: __lowerCamelCase : Dict = ksize + 1 __lowerCamelCase : int = np.zeros((ksize, ksize), dtype=np.floataa ) # each value for y in range(_lowercase ): for x in range(_lowercase ): # distance from center __lowerCamelCase : Dict = x - ksize // 2 __lowerCamelCase : Dict = y - ksize // 2 # degree to radiant __lowerCamelCase : Union[str, Any] = theta / 180 * np.pi __lowerCamelCase : Any = np.cos(_theta ) __lowerCamelCase : Tuple = np.sin(_theta ) # get kernel x __lowerCamelCase : Tuple = cos_theta * px + sin_theta * py # get kernel y __lowerCamelCase : Dict = -sin_theta * px + cos_theta * py # fill kernel __lowerCamelCase : Union[str, Any] = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image UpperCAmelCase__ :Dict = imread("""../image_data/lena.jpg""") # turn image in gray scale value UpperCAmelCase__ :Union[str, Any] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges UpperCAmelCase__ :Optional[int] = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: UpperCAmelCase__ :int = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) UpperCAmelCase__ :Union[str, Any] = out / out.max() * 255 UpperCAmelCase__ :List[str] = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
150
0
from ...configuration_utils import PretrainedConfig from ...utils import logging __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class lowerCamelCase_ ( lowercase ): __lowercase : int = "transfo-xl" __lowercase : Optional[int] = ["mems"] __lowercase : Tuple = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self , lowerCamelCase_=26_77_35 , lowerCamelCase_=[2_00_00, 4_00_00, 20_00_00] , lowerCamelCase_=10_24 , lowerCamelCase_=10_24 , lowerCamelCase_=16 , lowerCamelCase_=64 , lowerCamelCase_=40_96 , lowerCamelCase_=4 , lowerCamelCase_=False , lowerCamelCase_=18 , lowerCamelCase_=16_00 , lowerCamelCase_=10_00 , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=0 , lowerCamelCase_=-1 , lowerCamelCase_=True , lowerCamelCase_=0.1 , lowerCamelCase_=0.0 , lowerCamelCase_=True , lowerCamelCase_="normal" , lowerCamelCase_=0.01 , lowerCamelCase_=0.01 , lowerCamelCase_=0.02 , lowerCamelCase_=1E-5 , lowerCamelCase_=0 , **lowerCamelCase_ , ) -> int: """simple docstring""" _UpperCamelCase = vocab_size _UpperCamelCase = [] self.cutoffs.extend(lowerCamelCase_ ) if proj_share_all_but_first: _UpperCamelCase = [False] + [True] * len(self.cutoffs ) else: _UpperCamelCase = [False] + [False] * len(self.cutoffs ) _UpperCamelCase = d_model _UpperCamelCase = d_embed _UpperCamelCase = d_head _UpperCamelCase = d_inner _UpperCamelCase = div_val _UpperCamelCase = pre_lnorm _UpperCamelCase = n_layer _UpperCamelCase = n_head _UpperCamelCase = mem_len _UpperCamelCase = same_length _UpperCamelCase = attn_type _UpperCamelCase = clamp_len _UpperCamelCase = sample_softmax _UpperCamelCase = adaptive _UpperCamelCase = dropout _UpperCamelCase = dropatt _UpperCamelCase = untie_r _UpperCamelCase = init _UpperCamelCase = init_range _UpperCamelCase = proj_init_std _UpperCamelCase = init_std _UpperCamelCase = layer_norm_epsilon super().__init__(eos_token_id=lowerCamelCase_ , **lowerCamelCase_ ) @property def lowercase ( self ) -> Tuple: """simple docstring""" logger.info(f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' ) return -1 @max_position_embeddings.setter def lowercase ( self , lowerCamelCase_ ) -> Optional[int]: """simple docstring""" raise NotImplementedError( f'''The model {self.model_type} is one of the few models that has no sequence length limit.''' )
714
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowerCamelCase_ ( lowercase , lowercase ): @register_to_config def __init__( self , *, lowerCamelCase_ = 4 , lowerCamelCase_ = 7_68 , lowerCamelCase_ , lowerCamelCase_ , ) -> int: """simple docstring""" super().__init__() _UpperCamelCase = nn.Parameter(torch.zeros(lowerCamelCase_ ) ) # parameters for additional clip time embeddings _UpperCamelCase = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) _UpperCamelCase = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) # parameters for encoder hidden states _UpperCamelCase = clip_extra_context_tokens _UpperCamelCase = nn.Linear( lowerCamelCase_ , self.clip_extra_context_tokens * cross_attention_dim ) _UpperCamelCase = nn.Linear(lowerCamelCase_ , lowerCamelCase_ ) _UpperCamelCase = nn.LayerNorm(lowerCamelCase_ ) def lowercase ( self , *, lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> int: """simple docstring""" if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings _UpperCamelCase = image_embeddings.shape[0] _UpperCamelCase = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) _UpperCamelCase = classifier_free_guidance_embeddings.expand( lowerCamelCase_ , -1 ) _UpperCamelCase = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] _UpperCamelCase = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... _UpperCamelCase = self.embedding_proj(lowerCamelCase_ ) _UpperCamelCase = self.clip_image_embeddings_project_to_time_embeddings(lowerCamelCase_ ) _UpperCamelCase = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" _UpperCamelCase = self.clip_extra_context_tokens_proj(lowerCamelCase_ ) _UpperCamelCase = clip_extra_context_tokens.reshape(lowerCamelCase_ , -1 , self.clip_extra_context_tokens ) _UpperCamelCase = clip_extra_context_tokens.permute(0 , 2 , 1 ) _UpperCamelCase = self.encoder_hidden_states_proj(lowerCamelCase_ ) _UpperCamelCase = self.text_encoder_hidden_states_norm(lowerCamelCase_ ) _UpperCamelCase = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
589
0
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap __snake_case : Dict = 'Usage of script: script_name <size_of_canvas:int>' __snake_case : Optional[int] = [0] * 100 + [1] * 10 random.shuffle(choice) def __lowerCamelCase ( __snake_case : int ) -> int: """simple docstring""" A__ : Any =[[False for i in range(__a )] for j in range(__a )] return canvas def __lowerCamelCase ( __snake_case : list[list[bool]] ) -> Any: """simple docstring""" for i, row in enumerate(__a ): for j, _ in enumerate(__a ): A__ : Union[str, Any] =bool(random.getrandbits(1 ) ) def __lowerCamelCase ( __snake_case : list[list[bool]] ) -> Any: """simple docstring""" A__ : str =np.array(__a ) A__ : Tuple =np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(__a ): for c, pt in enumerate(__a ): A__ : Any =__judge_point( __a, current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) A__ : Any =next_gen_canvas del next_gen_canvas # cleaning memory as we move on. A__ : list[list[bool]] =current_canvas.tolist() return return_canvas def __lowerCamelCase ( __snake_case : bool, __snake_case : list[list[bool]] ) -> int: """simple docstring""" A__ : int =0 A__ : List[Any] =0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. A__ : Optional[Any] =pt if pt: if alive < 2: A__ : Optional[int] =False elif alive == 2 or alive == 3: A__ : str =True elif alive > 3: A__ : Tuple =False else: if alive == 3: A__ : int =True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) __snake_case : int = int(sys.argv[1]) # main working structure of this module. __snake_case : Union[str, Any] = create_canvas(canvas_size) seed(c) __snake_case , __snake_case : Tuple = plt.subplots() fig.show() __snake_case : Optional[int] = ListedColormap(['w', 'k']) try: while True: __snake_case : Union[str, Any] = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
215
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = {"""configuration_opt""": ["""OPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """OPTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ """OPT_PRETRAINED_MODEL_ARCHIVE_LIST""", """OPTForCausalLM""", """OPTModel""", """OPTPreTrainedModel""", """OPTForSequenceClassification""", """OPTForQuestionAnswering""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ["""TFOPTForCausalLM""", """TFOPTModel""", """TFOPTPreTrainedModel"""] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ """FlaxOPTForCausalLM""", """FlaxOPTModel""", """FlaxOPTPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys a_ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
437
0
'''simple docstring''' def A_ ( _lowerCAmelCase : float , _lowerCAmelCase : int ): """simple docstring""" if digit_amount > 0: return round(number - int(_lowerCAmelCase ) , _lowerCAmelCase ) return number - int(_lowerCAmelCase ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
11
'''simple docstring''' from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__) UpperCAmelCase_ : Optional[int] = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } UpperCAmelCase_ : Union[str, Any] = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } UpperCAmelCase_ : Union[str, Any] = { 'facebook/blenderbot_small-90M': 512, } class UpperCAmelCase__ ( A ): lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = BlenderbotSmallTokenizer def __init__( self : Optional[Any],__A : str=None,__A : str=None,__A : int="<|endoftext|>",__A : List[str]="<|endoftext|>",__A : Optional[Any]="<|endoftext|>",__A : Union[str, Any]=False,__A : List[Any]=True,**__A : str,): super().__init__( ByteLevelBPETokenizer( vocab=__A,merges=__A,add_prefix_space=__A,trim_offsets=__A,),bos_token=__A,eos_token=__A,unk_token=__A,**__A,) _lowerCamelCase : List[Any] = add_prefix_space def lowerCamelCase_ ( self : Any,__A : Optional[Any],__A : Optional[int]=None ): _lowerCamelCase : Any = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowerCamelCase_ ( self : List[Any],__A : List[int],__A : Optional[List[int]] = None ): _lowerCamelCase : Any = [self.sep_token_id] _lowerCamelCase : Union[str, 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]
11
1
from collections import Counter from pathlib import Path from typing import Optional, Tuple import yaml class lowerCamelCase__ ( yaml.SafeLoader): '''simple docstring''' def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Optional[int]: """simple docstring""" lowerCAmelCase__ : Any = [self.constructed_objects[key_node] for key_node, _ in node.value] lowerCAmelCase__ : Optional[Any] = [tuple(lowerCamelCase__ ) if isinstance(lowerCamelCase__ ,lowerCamelCase__ ) else key for key in keys] lowerCAmelCase__ : Any = Counter(lowerCamelCase__ ) lowerCAmelCase__ : Any = [key for key in counter if counter[key] > 1] if duplicate_keys: raise TypeError(f"""Got duplicate yaml keys: {duplicate_keys}""" ) def lowerCAmelCase__ (self ,__lowerCamelCase ,__lowerCamelCase=False ) -> str: """simple docstring""" lowerCAmelCase__ : int = super().construct_mapping(lowerCamelCase__ ,deep=lowerCamelCase__ ) self._check_no_duplicates_on_constructed_node(lowerCamelCase__ ) return mapping def lowerCAmelCase__ ( lowerCamelCase_ : List[str]): '''simple docstring''' lowerCAmelCase__ : Optional[int] = list(readme_content.splitlines()) if full_content and full_content[0] == "---" and "---" in full_content[1:]: lowerCAmelCase__ : str = full_content[1:].index('''---''') + 1 lowerCAmelCase__ : Optional[Any] = '''\n'''.join(full_content[1:sep_idx]) return yamlblock, "\n".join(full_content[sep_idx + 1 :]) return None, "\n".join(lowerCamelCase_) class lowerCamelCase__ ( __lowerCamelCase): '''simple docstring''' snake_case_ ={'train_eval_index'} # train-eval-index in the YAML metadata @classmethod def lowerCAmelCase__ (cls ,__lowerCamelCase ) -> "DatasetMetadata": """simple docstring""" with open(lowerCamelCase__ ,encoding='''utf-8''' ) as readme_file: lowerCAmelCase__ , lowerCAmelCase__ : str = _split_yaml_from_readme(readme_file.read() ) if yaml_string is not None: return cls.from_yaml_string(lowerCamelCase__ ) else: return cls() def lowerCAmelCase__ (self ,__lowerCamelCase ) -> Tuple: """simple docstring""" if path.exists(): with open(lowerCamelCase__ ,encoding='''utf-8''' ) as readme_file: lowerCAmelCase__ : Dict = readme_file.read() else: lowerCAmelCase__ : str = None lowerCAmelCase__ : List[str] = self._to_readme(lowerCamelCase__ ) with open(lowerCamelCase__ ,'''w''' ,encoding='''utf-8''' ) as readme_file: readme_file.write(lowerCamelCase__ ) def lowerCAmelCase__ (self ,__lowerCamelCase = None ) -> str: """simple docstring""" if readme_content is not None: lowerCAmelCase__ , lowerCAmelCase__ : List[Any] = _split_yaml_from_readme(lowerCamelCase__ ) lowerCAmelCase__ : Any = '''---\n''' + self.to_yaml_string() + '''---\n''' + content else: lowerCAmelCase__ : int = '''---\n''' + self.to_yaml_string() + '''---\n''' return full_content @classmethod def lowerCAmelCase__ (cls ,__lowerCamelCase ) -> "DatasetMetadata": """simple docstring""" lowerCAmelCase__ : int = yaml.load(lowerCamelCase__ ,Loader=_NoDuplicateSafeLoader ) or {} # Convert the YAML keys to DatasetMetadata fields lowerCAmelCase__ : List[Any] = { (key.replace('''-''' ,'''_''' ) if key.replace('''-''' ,'''_''' ) in cls._FIELDS_WITH_DASHES else key): value for key, value in metadata_dict.items() } return cls(**lowerCamelCase__ ) def lowerCAmelCase__ (self ) -> str: """simple docstring""" return yaml.safe_dump( { (key.replace('''_''' ,'''-''' ) if key in self._FIELDS_WITH_DASHES else key): value for key, value in self.items() } ,sort_keys=lowerCamelCase__ ,allow_unicode=lowerCamelCase__ ,encoding='''utf-8''' ,).decode('''utf-8''' ) __snake_case : str ={ 'image-classification': [], 'translation': [], 'image-segmentation': [], 'fill-mask': [], 'automatic-speech-recognition': [], 'token-classification': [], 'sentence-similarity': [], 'audio-classification': [], 'question-answering': [], 'summarization': [], 'zero-shot-classification': [], 'table-to-text': [], 'feature-extraction': [], 'other': [], 'multiple-choice': [], 'text-classification': [], 'text-to-image': [], 'text2text-generation': [], 'zero-shot-image-classification': [], 'tabular-classification': [], 'tabular-regression': [], 'image-to-image': [], 'tabular-to-text': [], 'unconditional-image-generation': [], 'text-retrieval': [], 'text-to-speech': [], 'object-detection': [], 'audio-to-audio': [], 'text-generation': [], 'conversational': [], 'table-question-answering': [], 'visual-question-answering': [], 'image-to-text': [], 'reinforcement-learning': [], 'voice-activity-detection': [], 'time-series-forecasting': [], 'document-question-answering': [], } if __name__ == "__main__": from argparse import ArgumentParser __snake_case : Tuple =ArgumentParser(usage='Validate the yaml metadata block of a README.md file.') ap.add_argument('readme_filepath') __snake_case : Dict =ap.parse_args() __snake_case : Optional[Any] =Path(args.readme_filepath) __snake_case : Optional[int] =DatasetMetadata.from_readme(readme_filepath) print(dataset_metadata) dataset_metadata.to_readme(readme_filepath)
647
import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class _lowercase ( unittest.TestCase ): def __init__( self : List[str] , lowerCamelCase__ : List[str] , lowerCamelCase__ : bool = True , lowerCamelCase__ : Dict[str, int] = None , lowerCamelCase__ : int = 3_2 , lowerCamelCase__ : bool = True , lowerCamelCase__ : Union[int, float] = 1 / 2_5_5 , lowerCamelCase__ : bool = True , lowerCamelCase__ : bool = True , lowerCamelCase__ : Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073] , lowerCamelCase__ : Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711] , lowerCamelCase__ : bool = True , lowerCamelCase__ : List[str]=7 , lowerCamelCase__ : int=3_0 , lowerCamelCase__ : List[Any]=4_0_0 , lowerCamelCase__ : int=3 , ) -> Optional[Any]: """simple docstring""" A_ = parent A_ = do_resize A_ = size if size is not None else {'''shortest_edge''': 2_8_8} A_ = size_divisor A_ = do_rescale A_ = rescale_factor A_ = do_normalize A_ = do_center_crop A_ = image_mean A_ = image_std A_ = do_pad A_ = batch_size A_ = num_channels A_ = min_resolution A_ = max_resolution def UpperCamelCase ( self : str ) -> int: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def UpperCamelCase ( self : List[str] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : int=False ) -> Dict: """simple docstring""" if not batched: A_ = self.size['''shortest_edge'''] A_ = image_inputs[0] if isinstance(lowerCamelCase__ , Image.Image ): A_ ,A_ = image.size else: A_ ,A_ = image.shape[1], image.shape[2] A_ = size / min(lowerCamelCase__ , lowerCamelCase__ ) if h < w: A_ ,A_ = size, scale * w else: A_ ,A_ = scale * h, size A_ = int((1_3_3_3 / 8_0_0) * size ) if max(lowerCamelCase__ , lowerCamelCase__ ) > max_size: A_ = max_size / max(lowerCamelCase__ , lowerCamelCase__ ) A_ = newh * scale A_ = neww * scale A_ ,A_ = int(newh + 0.5 ), int(neww + 0.5 ) A_ ,A_ = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: A_ = [] for image in image_inputs: A_ ,A_ = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) A_ = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[0] )[0] A_ = max(lowerCamelCase__ , key=lambda lowerCamelCase__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _lowercase ( __lowerCamelCase,unittest.TestCase ): _lowercase : List[str] = BridgeTowerImageProcessor if is_vision_available() else None def UpperCamelCase ( self : int ) -> Tuple: """simple docstring""" A_ = BridgeTowerImageProcessingTester(self ) @property def UpperCamelCase ( self : str ) -> Optional[int]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def UpperCamelCase ( self : Tuple ) -> List[Any]: """simple docstring""" A_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowerCamelCase__ , '''image_mean''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''image_std''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''do_normalize''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''do_resize''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''size''' ) ) self.assertTrue(hasattr(lowerCamelCase__ , '''size_divisor''' ) ) def UpperCamelCase ( self : Optional[int] ) -> str: """simple docstring""" pass def UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" A_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , Image.Image ) # Test not batched input A_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase ( self : str ) -> Optional[int]: """simple docstring""" A_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , numpify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , np.ndarray ) # Test not batched input A_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def UpperCamelCase ( self : Union[str, Any] ) -> int: """simple docstring""" A_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowerCamelCase__ , torchify=lowerCamelCase__ ) for image in image_inputs: self.assertIsInstance(lowerCamelCase__ , torch.Tensor ) # Test not batched input A_ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched A_ = image_processing(lowerCamelCase__ , return_tensors='''pt''' ).pixel_values A_ ,A_ = self.image_processor_tester.get_expected_values(lowerCamelCase__ , batched=lowerCamelCase__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
203
0
import qiskit def lowerCamelCase_ ( lowerCAmelCase: int , lowerCAmelCase: int )-> qiskit.result.counts.Counts: _snake_case : Any = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register _snake_case : Union[str, Any] = qiskit.QuantumCircuit(lowerCAmelCase , lowerCAmelCase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator _snake_case : int = qiskit.execute(lowerCAmelCase , lowerCAmelCase , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(lowerCAmelCase ) if __name__ == "__main__": lowerCAmelCase_ = single_qubit_measure(2, 2) print(F"""Total count for various states are: {counts}""")
669
from functools import reduce lowerCAmelCase_ = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def lowerCamelCase_ ( lowerCAmelCase: str = N )-> int: return max( # mypy cannot properly interpret reduce int(reduce(lambda lowerCAmelCase , lowerCAmelCase : str(int(lowerCAmelCase ) * int(lowerCAmelCase ) ) , n[i : i + 13] ) ) for i in range(len(lowerCAmelCase ) - 12 ) ) if __name__ == "__main__": print(F"""{solution() = }""")
669
1
import copy import inspect import unittest from transformers import AutoBackbone from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import require_timm, require_torch, torch_device from transformers.utils.import_utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor if is_torch_available(): import torch from transformers import TimmBackbone, TimmBackboneConfig from ...test_pipeline_mixin import PipelineTesterMixin class __SCREAMING_SNAKE_CASE : def __init__( self, _a, _a=None, _a=None, _a=None, _a="resnet50", _a=3, _a=32, _a=3, _a=True, _a=True, ) -> Dict: __SCREAMING_SNAKE_CASE = parent __SCREAMING_SNAKE_CASE = out_indices if out_indices is not None else [4] __SCREAMING_SNAKE_CASE = stage_names __SCREAMING_SNAKE_CASE = out_features __SCREAMING_SNAKE_CASE = backbone __SCREAMING_SNAKE_CASE = batch_size __SCREAMING_SNAKE_CASE = image_size __SCREAMING_SNAKE_CASE = num_channels __SCREAMING_SNAKE_CASE = use_pretrained_backbone __SCREAMING_SNAKE_CASE = is_training def __lowerCAmelCase ( self ) -> List[Any]: __SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values def __lowerCAmelCase ( self ) -> int: return TimmBackboneConfig( image_size=self.image_size, num_channels=self.num_channels, out_features=self.out_features, out_indices=self.out_indices, stage_names=self.stage_names, use_pretrained_backbone=self.use_pretrained_backbone, backbone=self.backbone, ) def __lowerCAmelCase ( self, _a, _a ) -> Optional[Any]: __SCREAMING_SNAKE_CASE = TimmBackbone(config=lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): __SCREAMING_SNAKE_CASE = model(lowercase__ ) self.parent.assertEqual( result.feature_map[-1].shape, (self.batch_size, model.channels[-1], 14, 14), ) def __lowerCAmelCase ( self ) -> Dict: __SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE = config_and_inputs __SCREAMING_SNAKE_CASE = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch @require_timm class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): SCREAMING_SNAKE_CASE__ =(TimmBackbone,) if is_torch_available() else () SCREAMING_SNAKE_CASE__ ={'''feature-extraction''': TimmBackbone} if is_torch_available() else {} SCREAMING_SNAKE_CASE__ =False SCREAMING_SNAKE_CASE__ =False SCREAMING_SNAKE_CASE__ =False SCREAMING_SNAKE_CASE__ =False def __lowerCAmelCase ( self ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE = TimmBackboneModelTester(self ) __SCREAMING_SNAKE_CASE = ConfigTester(self, config_class=lowercase__, has_text_modality=lowercase__ ) def __lowerCAmelCase ( self ) -> List[Any]: 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 __lowerCAmelCase ( self ) -> int: __SCREAMING_SNAKE_CASE = '''resnet18''' __SCREAMING_SNAKE_CASE = '''microsoft/resnet-18''' __SCREAMING_SNAKE_CASE = AutoBackbone.from_pretrained(lowercase__, use_timm_backbone=lowercase__ ) __SCREAMING_SNAKE_CASE = AutoBackbone.from_pretrained(lowercase__ ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(len(timm_model.stage_names ), len(transformers_model.stage_names ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) # Out indices are set to the last layer by default. For timm models, we don't know # the number of layers in advance, so we set it to (-1,), whereas for transformers # models, we set it to [len(stage_names) - 1] (kept for backward compatibility). self.assertEqual(timm_model.out_indices, (-1,) ) self.assertEqual(transformers_model.out_indices, [len(timm_model.stage_names ) - 1] ) __SCREAMING_SNAKE_CASE = AutoBackbone.from_pretrained(lowercase__, use_timm_backbone=lowercase__, out_indices=[1, 2, 3] ) __SCREAMING_SNAKE_CASE = AutoBackbone.from_pretrained(lowercase__, out_indices=[1, 2, 3] ) self.assertEqual(timm_model.out_indices, transformers_model.out_indices ) self.assertEqual(len(timm_model.out_features ), len(transformers_model.out_features ) ) self.assertEqual(timm_model.channels, transformers_model.channels ) @unittest.skip("TimmBackbone doesn\'t support feed forward chunking" ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip("TimmBackbone doesn\'t have num_hidden_layers attribute" ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip("TimmBackbone initialization is managed on the timm side" ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip("TimmBackbone models doesn\'t have inputs_embeds" ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip("TimmBackbone models doesn\'t have inputs_embeds" ) def __lowerCAmelCase ( self ) -> int: pass @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint" ) def __lowerCAmelCase ( self ) -> int: pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def __lowerCAmelCase ( self ) -> str: pass @unittest.skip("model weights aren\'t tied in TimmBackbone." ) def __lowerCAmelCase ( self ) -> List[Any]: pass @unittest.skip("model weights aren\'t tied in TimmBackbone." ) def __lowerCAmelCase ( self ) -> Any: pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def __lowerCAmelCase ( self ) -> List[str]: pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def __lowerCAmelCase ( self ) -> str: pass @unittest.skip("TimmBackbone doesn\'t have hidden size info in its configuration." ) def __lowerCAmelCase ( self ) -> List[Any]: pass @unittest.skip("TimmBackbone doesn\'t support output_attentions." ) def __lowerCAmelCase ( self ) -> Optional[Any]: pass @unittest.skip("Safetensors is not supported by timm." ) def __lowerCAmelCase ( self ) -> Union[str, Any]: pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __lowerCAmelCase ( self ) -> List[str]: pass def __lowerCAmelCase ( self ) -> int: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(lowercase__ ) __SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE = ['''pixel_values'''] self.assertListEqual(arg_names[:1], lowercase__ ) def __lowerCAmelCase ( self ) -> str: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = self.has_attentions # no need to test all models as different heads yield the same functionality __SCREAMING_SNAKE_CASE = self.all_model_classes[0] __SCREAMING_SNAKE_CASE = model_class(lowercase__ ) model.to(lowercase__ ) __SCREAMING_SNAKE_CASE = self._prepare_for_class(lowercase__, lowercase__ ) __SCREAMING_SNAKE_CASE = model(**lowercase__ ) __SCREAMING_SNAKE_CASE = outputs[0][-1] # Encoder-/Decoder-only models __SCREAMING_SNAKE_CASE = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: __SCREAMING_SNAKE_CASE = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowercase__ ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def __lowerCAmelCase ( self ) -> Any: __SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(**lowercase__ ) self.assertEqual(len(result.feature_maps ), len(config.out_indices ) ) self.assertEqual(len(model.channels ), len(config.out_indices ) ) # Check output of last stage is taken if out_features=None, out_indices=None __SCREAMING_SNAKE_CASE = copy.deepcopy(lowercase__ ) __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(**lowercase__ ) self.assertEqual(len(result.feature_maps ), 1 ) self.assertEqual(len(model.channels ), 1 ) # Check backbone can be initialized with fresh weights __SCREAMING_SNAKE_CASE = copy.deepcopy(lowercase__ ) __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() __SCREAMING_SNAKE_CASE = model(**lowercase__ )
693
import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase : def __init__( self , lowercase__ , lowercase__=1_3 , lowercase__=7 , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=True , lowercase__=9_9 , lowercase__=2_4 , lowercase__=2 , lowercase__=6 , lowercase__=3_7 , lowercase__="gelu" , lowercase__=0.1 , lowercase__=0.1 , lowercase__=5_1_2 , lowercase__=1_6 , lowercase__=2 , lowercase__=0.0_2 , lowercase__=3 , lowercase__=None , lowercase__=1_0_0_0 , ): __UpperCAmelCase : int = parent __UpperCAmelCase : Optional[int] = batch_size __UpperCAmelCase : Any = seq_length __UpperCAmelCase : Dict = is_training __UpperCAmelCase : str = use_input_mask __UpperCAmelCase : Dict = use_token_type_ids __UpperCAmelCase : Tuple = use_labels __UpperCAmelCase : Union[str, Any] = vocab_size __UpperCAmelCase : Tuple = hidden_size __UpperCAmelCase : Dict = num_hidden_layers __UpperCAmelCase : Optional[Any] = num_attention_heads __UpperCAmelCase : Union[str, Any] = intermediate_size __UpperCAmelCase : Optional[int] = hidden_act __UpperCAmelCase : int = hidden_dropout_prob __UpperCAmelCase : List[Any] = attention_probs_dropout_prob __UpperCAmelCase : List[Any] = max_position_embeddings __UpperCAmelCase : Optional[Any] = type_vocab_size __UpperCAmelCase : Optional[Any] = type_sequence_label_size __UpperCAmelCase : str = initializer_range __UpperCAmelCase : str = num_labels __UpperCAmelCase : str = scope __UpperCAmelCase : Union[str, Any] = range_bbox def A( self): __UpperCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __UpperCAmelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox) # Ensure that bbox is legal for i in range(bbox.shape[0]): for j in range(bbox.shape[1]): if bbox[i, j, 3] < bbox[i, j, 1]: __UpperCAmelCase : Optional[int] = bbox[i, j, 3] __UpperCAmelCase : str = bbox[i, j, 1] __UpperCAmelCase : Union[str, Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: __UpperCAmelCase : Optional[int] = bbox[i, j, 2] __UpperCAmelCase : int = bbox[i, j, 0] __UpperCAmelCase : Dict = t __UpperCAmelCase : Tuple = None if self.use_input_mask: __UpperCAmelCase : Any = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2) __UpperCAmelCase : List[Any] = None if self.use_token_type_ids: __UpperCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __UpperCAmelCase : List[str] = None __UpperCAmelCase : Union[str, Any] = None if self.use_labels: __UpperCAmelCase : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size) __UpperCAmelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __UpperCAmelCase : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def A( self): return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def A( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): __UpperCAmelCase : List[Any] = LiltModel(config=lowercase__) model.to(lowercase__) model.eval() __UpperCAmelCase : List[Any] = model(lowercase__ , bbox=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__) __UpperCAmelCase : Optional[int] = model(lowercase__ , bbox=lowercase__ , token_type_ids=lowercase__) __UpperCAmelCase : Optional[int] = model(lowercase__ , bbox=lowercase__) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size)) def A( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): __UpperCAmelCase : Optional[int] = self.num_labels __UpperCAmelCase : Dict = LiltForTokenClassification(config=lowercase__) model.to(lowercase__) model.eval() __UpperCAmelCase : Dict = model( lowercase__ , bbox=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , labels=lowercase__) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def A( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , ): __UpperCAmelCase : Dict = LiltForQuestionAnswering(config=lowercase__) model.to(lowercase__) model.eval() __UpperCAmelCase : List[Any] = model( lowercase__ , bbox=lowercase__ , attention_mask=lowercase__ , token_type_ids=lowercase__ , start_positions=lowercase__ , end_positions=lowercase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length)) def A( self): __UpperCAmelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ( __UpperCAmelCase ) , ) : Any = config_and_inputs __UpperCAmelCase : int = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): _lowerCAmelCase : str = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) _lowerCAmelCase : str = ( { '''feature-extraction''': LiltModel, '''question-answering''': LiltForQuestionAnswering, '''text-classification''': LiltForSequenceClassification, '''token-classification''': LiltForTokenClassification, '''zero-shot''': LiltForSequenceClassification, } if is_torch_available() else {} ) _lowerCAmelCase : Any = False _lowerCAmelCase : List[Any] = False def A( self , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__): return True def A( self): __UpperCAmelCase : Tuple = LiltModelTester(self) __UpperCAmelCase : List[Any] = ConfigTester(self , config_class=lowercase__ , hidden_size=3_7) def A( self): self.config_tester.run_common_tests() def A( self): __UpperCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__) def A( self): __UpperCAmelCase : int = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCAmelCase : Any = type self.model_tester.create_and_check_model(*lowercase__) def A( self): __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*lowercase__) def A( self): __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*lowercase__) @slow def A( self): for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase : Optional[Any] = LiltModel.from_pretrained(lowercase__) self.assertIsNotNone(lowercase__) @require_torch @slow class lowerCamelCase ( unittest.TestCase ): def A( self): __UpperCAmelCase : Any = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''').to(lowercase__) __UpperCAmelCase : str = torch.tensor([[1, 2]] , device=lowercase__) __UpperCAmelCase : List[str] = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=lowercase__) # forward pass with torch.no_grad(): __UpperCAmelCase : Dict = model(input_ids=lowercase__ , bbox=lowercase__) __UpperCAmelCase : List[Any] = torch.Size([1, 2, 7_6_8]) __UpperCAmelCase : Union[str, Any] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=lowercase__ , ) self.assertTrue(outputs.last_hidden_state.shape , lowercase__) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , lowercase__ , atol=1e-3))
462
0
from typing import Optional, Tuple, Union import torch from einops import rearrange, reduce from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput SCREAMING_SNAKE_CASE : Optional[int] = 8 def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=BITS ) -> List[str]: _lowercase : Optional[int] = x.device _lowercase : Dict = (x * 255).int().clamp(0 , 255 ) _lowercase : Union[str, Any] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCamelCase_ ) _lowercase : int = rearrange(lowerCamelCase_ , 'd -> d 1 1' ) _lowercase : List[str] = rearrange(lowerCamelCase_ , 'b c h w -> b c 1 h w' ) _lowercase : Tuple = ((x & mask) != 0).float() _lowercase : Optional[int] = rearrange(lowerCamelCase_ , 'b c d h w -> b (c d) h w' ) _lowercase : Tuple = bits * 2 - 1 return bits def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=BITS ) -> List[Any]: _lowercase : Tuple = x.device _lowercase : Dict = (x > 0).int() _lowercase : Dict = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCamelCase_ , dtype=torch.intaa ) _lowercase : Optional[Any] = rearrange(lowerCamelCase_ , 'd -> d 1 1' ) _lowercase : Optional[int] = rearrange(lowerCamelCase_ , 'b (c d) h w -> b c d h w' , d=8 ) _lowercase : Optional[Any] = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' ) return (dec / 255).clamp(0.0 , 1.0 ) def UpperCamelCase_( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 0.0 , lowerCamelCase_ = True , lowerCamelCase_=None , lowerCamelCase_ = True , ) -> Union[DDIMSchedulerOutput, Tuple]: if self.num_inference_steps is None: raise ValueError( 'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) _lowercase : List[Any] = timestep - self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas _lowercase : List[Any] = self.alphas_cumprod[timestep] _lowercase : Any = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod _lowercase : List[Any] = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _lowercase : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 # 4. Clip "predicted x_0" _lowercase : Optional[Any] = self.bit_scale if self.config.clip_sample: _lowercase : List[str] = torch.clamp(lowerCamelCase_ , -scale , lowerCamelCase_ ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) _lowercase : List[Any] = self._get_variance(lowerCamelCase_ , lowerCamelCase_ ) _lowercase : List[Any] = eta * variance ** 0.5 if use_clipped_model_output: # the model_output is always re-derived from the clipped x_0 in Glide _lowercase : str = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _lowercase : Optional[int] = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf _lowercase : Optional[int] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if eta > 0: # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 _lowercase : List[str] = model_output.device if torch.is_tensor(lowerCamelCase_ ) else 'cpu' _lowercase : Union[str, Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=lowerCamelCase_ ).to(lowerCamelCase_ ) _lowercase : Tuple = self._get_variance(lowerCamelCase_ , lowerCamelCase_ ) ** 0.5 * eta * noise _lowercase : str = prev_sample + variance if not return_dict: return (prev_sample,) return DDIMSchedulerOutput(prev_sample=lowerCamelCase_ , pred_original_sample=lowerCamelCase_ ) def UpperCamelCase_( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_="epsilon" , lowerCamelCase_=None , lowerCamelCase_ = True , ) -> Union[DDPMSchedulerOutput, Tuple]: _lowercase : Dict = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]: _lowercase , _lowercase : str = torch.split(lowerCamelCase_ , sample.shape[1] , dim=1 ) else: _lowercase : Union[str, Any] = None # 1. compute alphas, betas _lowercase : Dict = self.alphas_cumprod[t] _lowercase : Any = self.alphas_cumprod[t - 1] if t > 0 else self.one _lowercase : List[str] = 1 - alpha_prod_t _lowercase : List[str] = 1 - alpha_prod_t_prev # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if prediction_type == "epsilon": _lowercase : List[str] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif prediction_type == "sample": _lowercase : List[Any] = model_output else: raise ValueError(F'''Unsupported prediction_type {prediction_type}.''' ) # 3. Clip "predicted x_0" _lowercase : int = self.bit_scale if self.config.clip_sample: _lowercase : Tuple = torch.clamp(lowerCamelCase_ , -scale , lowerCamelCase_ ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _lowercase : Tuple = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t _lowercase : Tuple = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf _lowercase : Tuple = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise _lowercase : Dict = 0 if t > 0: _lowercase : List[Any] = torch.randn( model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=lowerCamelCase_ ).to(model_output.device ) _lowercase : int = (self._get_variance(lowerCamelCase_ , predicted_variance=lowerCamelCase_ ) ** 0.5) * noise _lowercase : str = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return DDPMSchedulerOutput(prev_sample=lowerCamelCase_ , pred_original_sample=lowerCamelCase_ ) class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase = 1.0, ) -> Any: """simple docstring""" super().__init__() _lowercase : Dict = bit_scale _lowercase : Tuple = ( ddim_bit_scheduler_step if isinstance(lowerCamelCase, lowerCamelCase) else ddpm_bit_scheduler_step ) self.register_modules(unet=lowerCamelCase, scheduler=lowerCamelCase) @torch.no_grad() def __call__( self, lowerCamelCase = 2_56, lowerCamelCase = 2_56, lowerCamelCase = 50, lowerCamelCase = None, lowerCamelCase = 1, lowerCamelCase = "pil", lowerCamelCase = True, **lowerCamelCase, ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" _lowercase : List[Any] = torch.randn( (batch_size, self.unet.config.in_channels, height, width), generator=lowerCamelCase, ) _lowercase : List[Any] = decimal_to_bits(lowerCamelCase) * self.bit_scale _lowercase : Optional[Any] = latents.to(self.device) self.scheduler.set_timesteps(lowerCamelCase) for t in self.progress_bar(self.scheduler.timesteps): # predict the noise residual _lowercase : Dict = self.unet(lowerCamelCase, lowerCamelCase).sample # compute the previous noisy sample x_t -> x_t-1 _lowercase : Optional[Any] = self.scheduler.step(lowerCamelCase, lowerCamelCase, lowerCamelCase).prev_sample _lowercase : Tuple = bits_to_decimal(lowerCamelCase) if output_type == "pil": _lowercase : Tuple = self.numpy_to_pil(lowerCamelCase) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase)
354
from jiwer import compute_measures import datasets SCREAMING_SNAKE_CASE : Tuple = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" SCREAMING_SNAKE_CASE : Optional[Any] = "\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n" SCREAMING_SNAKE_CASE : Any = "\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> wer = datasets.load_metric(\"wer\")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _lowerCamelCase( datasets.Metric ): def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Value('string', id='sequence'), 'references': datasets.Value('string', id='sequence'), }), codebase_urls=['https://github.com/jitsi/jiwer/'], reference_urls=[ 'https://en.wikipedia.org/wiki/Word_error_rate', ], ) def UpperCamelCase ( self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=False) -> Optional[Any]: """simple docstring""" if concatenate_texts: return compute_measures(lowerCamelCase, lowerCamelCase)["wer"] else: _lowercase : Dict = 0 _lowercase : Optional[int] = 0 for prediction, reference in zip(lowerCamelCase, lowerCamelCase): _lowercase : List[Any] = compute_measures(lowerCamelCase, lowerCamelCase) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
354
1
"""simple docstring""" 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 _snake_case = logging.get_logger(__name__) class _a ( _lowercase ): a_ : List[str] = ['''pixel_values'''] def __init__( self : Dict , 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__ : int , ): super().__init__(**__A ) lowerCamelCase__ = size if size is not None else {"""shortest_edge""": 2_56} lowerCamelCase__ = get_size_dict(__A , default_to_square=__A ) lowerCamelCase__ = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24} lowerCamelCase__ = get_size_dict(__A , param_name='crop_size' ) lowerCamelCase__ = do_resize lowerCamelCase__ = size lowerCamelCase__ = resample lowerCamelCase__ = do_center_crop lowerCamelCase__ = crop_size lowerCamelCase__ = do_rescale lowerCamelCase__ = rescale_factor lowerCamelCase__ = do_normalize lowerCamelCase__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN lowerCamelCase__ = image_std if image_std is not None else IMAGENET_STANDARD_STD def _UpperCamelCase ( self : Optional[Any] , 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__ : List[Any] , ): lowerCamelCase__ = get_size_dict(__A , default_to_square=__A ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) lowerCamelCase__ = get_resize_output_image_size(__A , size=size['shortest_edge'] , default_to_square=__A ) return resize(__A , size=__A , resample=__A , data_format=__A , **__A ) def _UpperCamelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : Dict[str, int] , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : str , ): lowerCamelCase__ = get_size_dict(__A ) 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(__A , size=(size['height'], size['width']) , data_format=__A , **__A ) def _UpperCamelCase ( self : List[str] , SCREAMING_SNAKE_CASE__ : np.ndarray , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : Optional[Union[str, ChannelDimension]] = None , **SCREAMING_SNAKE_CASE__ : Optional[int] ): return rescale(__A , scale=__A , data_format=__A , **__A ) def _UpperCamelCase ( self : 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__ : Tuple , ): return normalize(__A , mean=__A , std=__A , data_format=__A , **__A ) def _UpperCamelCase ( self : int , 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__ : Optional[int] , ): lowerCamelCase__ = do_resize if do_resize is not None else self.do_resize lowerCamelCase__ = size if size is not None else self.size lowerCamelCase__ = get_size_dict(__A , default_to_square=__A ) lowerCamelCase__ = resample if resample is not None else self.resample lowerCamelCase__ = do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase__ = crop_size if crop_size is not None else self.crop_size lowerCamelCase__ = get_size_dict(__A , param_name='crop_size' ) lowerCamelCase__ = do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase__ = rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase__ = image_mean if image_mean is not None else self.image_mean lowerCamelCase__ = image_std if image_std is not None else self.image_std lowerCamelCase__ = make_list_of_images(__A ) if not valid_images(__A ): 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. lowerCamelCase__ = [to_numpy_array(__A ) for image in images] if do_resize: lowerCamelCase__ = [self.resize(image=__A , size=__A , resample=__A ) for image in images] if do_center_crop: lowerCamelCase__ = [self.center_crop(image=__A , size=__A ) for image in images] if do_rescale: lowerCamelCase__ = [self.rescale(image=__A , scale=__A ) for image in images] if do_normalize: lowerCamelCase__ = [self.normalize(image=__A , mean=__A , std=__A ) for image in images] lowerCamelCase__ = [to_channel_dimension_format(__A , __A ) for image in images] lowerCamelCase__ = {"""pixel_values""": images} return BatchFeature(data=__A , tensor_type=__A ) def _UpperCamelCase ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Tuple] = None ): lowerCamelCase__ = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(__A ) != len(__A ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(__A ): lowerCamelCase__ = target_sizes.numpy() lowerCamelCase__ = [] for idx in range(len(__A ) ): lowerCamelCase__ = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=__A ) lowerCamelCase__ = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(__A ) else: lowerCamelCase__ = logits.argmax(dim=1 ) lowerCamelCase__ = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
510
from typing import List, Optional import numpy as np from ...processing_utils import ProcessorMixin from ...utils import to_numpy class lowerCamelCase_ ( _lowercase ): _lowercase : Union[str, Any] = '''EncodecFeatureExtractor''' _lowercase : Any = ('''T5Tokenizer''', '''T5TokenizerFast''') def __init__( self : List[Any] , __A : Any , __A : Tuple ): super().__init__(__A , __A ) __A : Dict = self.feature_extractor __A : List[str] = False def lowerCAmelCase_ ( self : Union[str, Any] , __A : str=None , __A : Tuple=None , __A : Dict=True ): return self.tokenizer.get_decoder_prompt_ids(task=__A , language=__A , no_timestamps=__A ) def __call__( self : Optional[Any] , *__A : Tuple , **__A : Tuple ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__A , **__A ) __A : str = kwargs.pop("""audio""" , __A ) __A : Optional[Any] = kwargs.pop("""sampling_rate""" , __A ) __A : int = kwargs.pop("""text""" , __A ) if len(__A ) > 0: __A : int = args[0] __A : Dict = args[1:] if audio is None and text is None: raise ValueError("""You need to specify either an `audio` or `text` input to process.""" ) if text is not None: __A : Dict = self.tokenizer(__A , **__A ) if audio is not None: __A : Optional[int] = self.feature_extractor(__A , *__A , sampling_rate=__A , **__A ) if audio is None: return inputs elif text is None: return audio_inputs else: __A : List[Any] = audio_inputs["""input_values"""] if "padding_mask" in audio_inputs: __A : int = audio_inputs["""padding_mask"""] return inputs def lowerCAmelCase_ ( self : List[str] , *__A : int , **__A : Tuple ): __A : Optional[int] = kwargs.pop("""audio""" , __A ) __A : List[str] = kwargs.pop("""padding_mask""" , __A ) if len(__A ) > 0: __A : Dict = args[0] __A : Optional[int] = args[1:] if audio_values is not None: return self._decode_audio(__A , padding_mask=__A ) else: return self.tokenizer.batch_decode(*__A , **__A ) def lowerCAmelCase_ ( self : Optional[Any] , *__A : Dict , **__A : Any ): return self.tokenizer.decode(*__A , **__A ) def lowerCAmelCase_ ( self : Tuple , __A : Union[str, Any] , __A : Optional = None ): __A : List[str] = to_numpy(__A ) __A , __A , __A : Tuple = audio_values.shape if padding_mask is None: return list(__A ) __A : Union[str, Any] = to_numpy(__A ) # match the sequence length of the padding mask to the generated audio arrays by padding with the **non-padding** # token (so that the generated audio values are **not** treated as padded tokens) __A : List[str] = seq_len - padding_mask.shape[-1] __A : Tuple = 1 - self.feature_extractor.padding_value __A : Optional[int] = np.pad(__A , ((0, 0), (0, difference)) , """constant""" , constant_values=__A ) __A : int = audio_values.tolist() for i in range(__A ): __A : str = np.asarray(audio_values[i] )[ padding_mask[i][None, :] != self.feature_extractor.padding_value ] __A : List[Any] = sliced_audio.reshape(__A , -1 ) return audio_values
17
0
"""simple docstring""" __lowercase = {} def lowercase ( A_ , A_ , A_ )-> int: '''simple docstring''' 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 : List[Any] = (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 : Tuple = _calculate(days - 1 , A_ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 a : Optional[int] = _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter a : Any = _calculate(days - 1 , A_ , 0 ) a : List[Any] = state_late + state_absent + state_ontime a : Optional[Any] = prizestrings return prizestrings def lowercase ( A_ = 30 )-> int: '''simple docstring''' return _calculate(A_ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
135
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers __lowercase = float("""nan""") class _A : """simple docstring""" def __init__( self : List[str] , __UpperCAmelCase : Optional[int]): a : Any = sys.stdout a : Any = open(__UpperCAmelCase , "a") def __getattr__( self : Dict , __UpperCAmelCase : List[Any]): return getattr(self.stdout , __UpperCAmelCase) def __snake_case ( self : Any , __UpperCAmelCase : Any): self.stdout.write(__UpperCAmelCase) # strip tqdm codes self.file.write(re.sub(r"^.*\r" , "" , __UpperCAmelCase , 0 , re.M)) def lowercase ( A_=80 , A_=False )-> List[str]: '''simple docstring''' a : List[Any] = [] # deal with critical env vars a : List[Any] = ["CUDA_VISIBLE_DEVICES"] for key in env_keys: a : Any = os.environ.get(A_ , A_ ) if val is not None: cmd.append(F'''{key}={val}''' ) # python executable (not always needed if the script is executable) a : List[Any] = sys.executable if full_python_path else sys.executable.split("/" )[-1] cmd.append(A_ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes a : Any = [] a : Any = "" while len(A_ ) > 0: current_line += F'''{cmd.pop(0 )} ''' if len(A_ ) == 0 or len(A_ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(A_ ) a : List[Any] = "" return "\\\n".join(A_ ) def lowercase ( A_ , A_ )-> Tuple: '''simple docstring''' a : List[str] = re.sub(R"[\\\n]+" , " " , args.base_cmd ) # remove --output_dir if any and set our own a : Optional[int] = re.sub("--output_dir\s+[^\s]+" , "" , args.base_cmd ) args.base_cmd += F''' --output_dir {output_dir}''' # ensure we have --overwrite_output_dir a : Dict = re.sub("--overwrite_output_dir\s+" , "" , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def lowercase ( A_ , A_ , A_ , A_ , A_ , A_ , A_ )-> int: '''simple docstring''' if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 1_0.3_1, 1_0_0.2, 5_5.6_6_6_6, 2_2_2.2_2_2_2_2_2_2_2] )} , ) a : Optional[Any] = subprocess.run(A_ , capture_output=A_ , text=A_ ) if verbose: print("STDOUT" , result.stdout ) print("STDERR" , result.stderr ) # save the streams a : List[str] = variation.replace(" " , "-" ) with open(Path(A_ ) / F'''log.{prefix}.stdout.txt''' , "w" ) as f: f.write(result.stdout ) with open(Path(A_ ) / F'''log.{prefix}.stderr.txt''' , "w" ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print("failed" ) return {target_metric_key: nan} with io.open(F'''{output_dir}/all_results.json''' , "r" , encoding="utf-8" ) as f: a : Dict = json.load(A_ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} def lowercase ( A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , )-> Tuple: '''simple docstring''' a : List[Any] = [] a : List[str] = [] a : Union[str, Any] = F'''{id}: {variation:<{longest_variation_len}}''' a : Any = F'''{preamble}: ''' a : Optional[Any] = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(A_ ) , desc=A_ , leave=A_ ): a : Dict = process_run_single( A_ , A_ , A_ , A_ , A_ , A_ , A_ ) a : Tuple = single_run_metrics[target_metric_key] if not math.isnan(A_ ): metrics.append(A_ ) results.append(A_ ) outcome += "✓" else: outcome += "✘" a : List[str] = F'''\33[2K\r{outcome}''' if len(A_ ) > 0: a : List[Any] = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} a : Tuple = round(mean_metrics[target_metric_key] , 2 ) a : Optional[int] = F'''{outcome} {mean_target}''' if len(A_ ) > 1: results_str += F''' {tuple(round(A_ , 2 ) for x in results )}''' print(A_ ) a : Optional[int] = variation return mean_metrics else: print(A_ ) return {variation_key: variation, target_metric_key: nan} def lowercase ( )-> Any: '''simple docstring''' a : int = torch.cuda.get_device_properties(torch.device("cuda" ) ) return F''' Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB ''' def lowercase ( A_ , A_ , A_ , A_ , A_ )-> List[str]: '''simple docstring''' a : Optional[Any] = pd.DataFrame(A_ ) a : Tuple = "variation" a : Union[str, Any] = "diff_%" a : Optional[Any] = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan a : List[str] = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(A_ ): # as a fallback, use the minimal value as the sentinel a : Optional[int] = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(A_ ): a : Tuple = df.apply( lambda A_ : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis="columns" , ) # re-order columns a : str = [variation_key, target_metric_key, diff_key, *report_metric_keys] a : Tuple = df.reindex(A_ , axis="columns" ) # reorder cols # capitalize a : Tuple = df.rename(str.capitalize , axis="columns" ) # make the cols as narrow as possible a : Dict = df.rename(lambda A_ : c.replace("_" , "<br>" ) , axis="columns" ) a : Tuple = df.rename(lambda A_ : c.replace("_" , "\n" ) , axis="columns" ) a : Dict = ["", "Copy between the cut-here-lines and paste as is to github or a forum"] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=A_ , floatfmt=".2f" )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=A_ , floatfmt=".2f" )] print("\n\n".join(A_ ) ) def lowercase ( )-> List[str]: '''simple docstring''' a : str = argparse.ArgumentParser() parser.add_argument( "--base-cmd" , default=A_ , type=A_ , required=A_ , help="Base cmd" , ) parser.add_argument( "--variations" , default=A_ , type=A_ , nargs="+" , required=A_ , help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'" , ) parser.add_argument( "--base-variation" , default=A_ , type=A_ , help="Baseline variation to compare to. if None the minimal target value will be used to compare against" , ) parser.add_argument( "--target-metric-key" , default=A_ , type=A_ , required=A_ , help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second" , ) parser.add_argument( "--report-metric-keys" , default="" , type=A_ , help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples" , ) parser.add_argument( "--repeat-times" , default=1 , type=A_ , help="How many times to re-run each variation - an average will be reported" , ) parser.add_argument( "--output_dir" , default="output_benchmark" , type=A_ , help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked" , ) parser.add_argument( "--verbose" , default=A_ , action="store_true" , help="Whether to show the outputs of each run or just the benchmark progress" , ) a : int = parser.parse_args() a : str = args.output_dir Path(A_ ).mkdir(exist_ok=A_ ) a : Tuple = get_base_command(A_ , A_ ) # split each dimension into its --foo variations a : Optional[int] = [list(map(str.strip , re.split(R"\|" , A_ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty a : Union[str, Any] = list(map(str.strip , map(" ".join , itertools.product(*A_ ) ) ) ) a : str = max(len(A_ ) for x in variations ) # split wanted keys a : Tuple = args.report_metric_keys.split() # capture prints into a log file for convenience a : Optional[int] = F'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt''' print(F'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''' ) print(F'''and this script\'s output is also piped into {report_fn}''' ) a : str = Tee(A_ ) print(F'''\n*** Running {len(A_ )} benchmarks:''' ) print(F'''Base command: {" ".join(A_ )}''' ) a : str = "variation" a : List[Any] = [] for id, variation in enumerate(tqdm(A_ , desc="Total completion: " , leave=A_ ) ): a : List[Any] = base_cmd + variation.split() results.append( process_run( id + 1 , A_ , A_ , A_ , A_ , args.target_metric_key , A_ , args.repeat_times , A_ , args.verbose , ) ) process_results(A_ , args.target_metric_key , A_ , args.base_variation , A_ ) if __name__ == "__main__": main()
135
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging __lowerCAmelCase =logging.get_logger(__name__) if is_vision_available(): import PIL class _snake_case ( snake_case ): """simple docstring""" _UpperCamelCase = ["pixel_values"] def __init__( self , UpperCAmelCase__ = True , UpperCAmelCase__ = None , UpperCAmelCase__ = PILImageResampling.BICUBIC , UpperCAmelCase__ = True , UpperCAmelCase__ = None , UpperCAmelCase__ = True , UpperCAmelCase__ = 1 / 255 , UpperCAmelCase__ = True , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = True , **UpperCAmelCase__ , ) -> None: super().__init__(**UpperCAmelCase__ ) a_ = size if size is not None else {'shortest_edge': 224} a_ = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) a_ = crop_size if crop_size is not None else {'height': 224, 'width': 224} a_ = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ , param_name='crop_size' ) a_ = do_resize a_ = size a_ = resample a_ = do_center_crop a_ = crop_size a_ = do_rescale a_ = rescale_factor a_ = do_normalize a_ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN a_ = image_std if image_std is not None else OPENAI_CLIP_STD a_ = do_convert_rgb def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = PILImageResampling.BICUBIC , UpperCAmelCase__ = None , **UpperCAmelCase__ , ) -> np.ndarray: a_ = get_size_dict(UpperCAmelCase__ , default_to_square=UpperCAmelCase__ ) if "shortest_edge" not in size: raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) a_ = get_resize_output_image_size(UpperCAmelCase__ , size=size['shortest_edge'] , default_to_square=UpperCAmelCase__ ) return resize(UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , **UpperCAmelCase__ , ) -> np.ndarray: a_ = get_size_dict(UpperCAmelCase__ ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(UpperCAmelCase__ , size=(size['height'], size['width']) , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , **UpperCAmelCase__ , ) -> Union[str, Any]: return rescale(UpperCAmelCase__ , scale=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , **UpperCAmelCase__ , ) -> np.ndarray: return normalize(UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ , data_format=UpperCAmelCase__ , **UpperCAmelCase__ ) def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase__ , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = None , UpperCAmelCase__ = ChannelDimension.FIRST , **UpperCAmelCase__ , ) -> PIL.Image.Image: a_ = do_resize if do_resize is not None else self.do_resize a_ = size if size is not None else self.size a_ = get_size_dict(UpperCAmelCase__ , param_name='size' , default_to_square=UpperCAmelCase__ ) a_ = resample if resample is not None else self.resample a_ = do_center_crop if do_center_crop is not None else self.do_center_crop a_ = crop_size if crop_size is not None else self.crop_size a_ = get_size_dict(UpperCAmelCase__ , param_name='crop_size' , default_to_square=UpperCAmelCase__ ) a_ = do_rescale if do_rescale is not None else self.do_rescale a_ = rescale_factor if rescale_factor is not None else self.rescale_factor a_ = do_normalize if do_normalize is not None else self.do_normalize a_ = image_mean if image_mean is not None else self.image_mean a_ = image_std if image_std is not None else self.image_std a_ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb a_ = make_list_of_images(UpperCAmelCase__ ) if not valid_images(UpperCAmelCase__ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # PIL RGBA images are converted to RGB if do_convert_rgb: a_ = [convert_to_rgb(UpperCAmelCase__ ) for image in images] # All transformations expect numpy arrays. a_ = [to_numpy_array(UpperCAmelCase__ ) for image in images] if do_resize: a_ = [self.resize(image=UpperCAmelCase__ , size=UpperCAmelCase__ , resample=UpperCAmelCase__ ) for image in images] if do_center_crop: a_ = [self.center_crop(image=UpperCAmelCase__ , size=UpperCAmelCase__ ) for image in images] if do_rescale: a_ = [self.rescale(image=UpperCAmelCase__ , scale=UpperCAmelCase__ ) for image in images] if do_normalize: a_ = [self.normalize(image=UpperCAmelCase__ , mean=UpperCAmelCase__ , std=UpperCAmelCase__ ) for image in images] a_ = [to_channel_dimension_format(UpperCAmelCase__ , UpperCAmelCase__ ) for image in images] a_ = {'pixel_values': images} return BatchFeature(data=UpperCAmelCase__ , tensor_type=UpperCAmelCase__ )
697
'''simple docstring''' def a ( _UpperCAmelCase = 5_0 ) -> int: """simple docstring""" a_ = [1] * (length + 1) for row_length in range(3 , length + 1 ): for block_length in range(3 , row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
697
1
import qiskit def lowerCAmelCase_ ( UpperCamelCase_ = 2 ) -> qiskit.result.counts.Counts: UpperCamelCase_ = qubits # Using Aer's simulator UpperCamelCase_ = qiskit.Aer.get_backend("aer_simulator" ) # Creating a Quantum Circuit acting on the q register UpperCamelCase_ = qiskit.QuantumCircuit(UpperCamelCase_ , UpperCamelCase_ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , UpperCamelCase_ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , UpperCamelCase_ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(UpperCamelCase_ ) ) , list(range(UpperCamelCase_ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator UpperCamelCase_ = qiskit.execute(UpperCamelCase_ , UpperCamelCase_ , shots=1000 ) return job.result().get_counts(UpperCamelCase_ ) if __name__ == "__main__": print(f'''Total count for various states are: {quantum_entanglement(3)}''')
721
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } _UpperCAmelCase = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } _UpperCAmelCase = { 'facebook/blenderbot_small-90M': 5_1_2, } class _UpperCamelCase ( lowerCAmelCase_ ): _UpperCamelCase : Optional[Any] = VOCAB_FILES_NAMES _UpperCamelCase : str = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase : str = BlenderbotSmallTokenizer def __init__( self: Dict , _SCREAMING_SNAKE_CASE: Optional[int]=None , _SCREAMING_SNAKE_CASE: List[str]=None , _SCREAMING_SNAKE_CASE: Optional[int]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: List[Any]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: List[str]="<|endoftext|>" , _SCREAMING_SNAKE_CASE: Optional[Any]=False , _SCREAMING_SNAKE_CASE: int=True , **_SCREAMING_SNAKE_CASE: Optional[int] , ) -> int: """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=_SCREAMING_SNAKE_CASE , merges=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , trim_offsets=_SCREAMING_SNAKE_CASE , ) , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) UpperCamelCase_ = add_prefix_space def lowercase ( self: Any , _SCREAMING_SNAKE_CASE: Any , _SCREAMING_SNAKE_CASE: Any=None ) -> List[str]: """simple docstring""" UpperCamelCase_ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase ( self: int , _SCREAMING_SNAKE_CASE: List[int] , _SCREAMING_SNAKE_CASE: Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCamelCase_ = [self.sep_token_id] UpperCamelCase_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
371
0
import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py snake_case_ = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. snake_case_ = direct_transformers_import(PATH_TO_TRANSFORMERS) snake_case_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING snake_case_ = { # used to compute the property `self.chunk_length` 'EncodecConfig': ['overlap'], # used as `self.bert_model = BertModel(config, ...)` 'DPRConfig': True, # not used in modeling files, but it's an important information 'FSMTConfig': ['langs'], # used internally in the configuration class file 'GPTNeoConfig': ['attention_types'], # used internally in the configuration class file 'EsmConfig': ['is_folding_model'], # used during training (despite we don't have training script for these models yet) 'Mask2FormerConfig': ['ignore_value'], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) 'OneFormerConfig': ['ignore_value', 'norm'], # used during preprocessing and collation, see `collating_graphormer.py` 'GraphormerConfig': ['spatial_pos_max'], # used internally in the configuration class file 'T5Config': ['feed_forward_proj'], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally 'MT5Config': ['feed_forward_proj', 'tokenizer_class'], 'UMT5Config': ['feed_forward_proj', 'tokenizer_class'], # used internally in the configuration class file 'LongT5Config': ['feed_forward_proj'], # used internally in the configuration class file 'SwitchTransformersConfig': ['feed_forward_proj'], # having default values other than `1e-5` - we can't fix them without breaking 'BioGptConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'GLPNConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'SegformerConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'CvtConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'PerceiverConfig': ['layer_norm_eps'], # used internally to calculate the feature size 'InformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'TimeSeriesTransformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'AutoformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate `mlp_dim` 'SamVisionConfig': ['mlp_ratio'], # For (head) training, but so far not implemented 'ClapAudioConfig': ['num_classes'], # Not used, but providing useful information to users 'SpeechT5HifiGanConfig': ['sampling_rate'], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { 'CLIPSegConfig': True, 'DeformableDetrConfig': True, 'DetaConfig': True, 'DinatConfig': True, 'DonutSwinConfig': True, 'EfficientFormerConfig': True, 'FSMTConfig': True, 'JukeboxConfig': True, 'LayoutLMv2Config': True, 'MaskFormerSwinConfig': True, 'MT5Config': True, 'NatConfig': True, 'OneFormerConfig': True, 'PerceiverConfig': True, 'RagConfig': True, 'SpeechT5Config': True, 'SwinConfig': True, 'Swin2SRConfig': True, 'Swinv2Config': True, 'SwitchTransformersConfig': True, 'TableTransformerConfig': True, 'TapasConfig': True, 'TransfoXLConfig': True, 'UniSpeechConfig': True, 'UniSpeechSatConfig': True, 'WavLMConfig': True, 'WhisperConfig': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) 'JukeboxPriorConfig': True, # TODO: @Younes (for `is_decoder`) 'Pix2StructTextConfig': True, } ) def lowerCamelCase__ ( snake_case_ : int , snake_case_ : Any , snake_case_ : List[str] , snake_case_ : str ) -> str: __snake_case = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f"""config.{attribute}""" in modeling_source or f"""getattr(config, \"{attribute}\"""" in modeling_source or f"""getattr(self.config, \"{attribute}\"""" in modeling_source ): __snake_case = True # Deal with multi-line cases elif ( re.search( Rf"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""" , _a , ) is not None ): __snake_case = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: __snake_case = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files __snake_case = [ '''bos_index''', '''eos_index''', '''pad_index''', '''unk_index''', '''mask_index''', '''image_size''', '''use_cache''', '''out_features''', '''out_indices''', ] __snake_case = ['''encoder_no_repeat_ngram_size'''] # Special cases to be allowed __snake_case = True if not attribute_used: __snake_case = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: __snake_case = True elif attribute in ["tie_word_embeddings"] and default_value is False: __snake_case = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: __snake_case = True elif attribute.endswith('''_token_id''' ): __snake_case = True # configuration class specific cases if not case_allowed: __snake_case = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) __snake_case = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowerCamelCase__ ( snake_case_ : int ) -> Dict: __snake_case = dict(inspect.signature(config_class.__init__ ).parameters ) __snake_case = [x for x in list(signature.keys() ) if x not in ['''self''', '''kwargs''']] __snake_case = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass __snake_case = {} if len(config_class.attribute_map ) > 0: __snake_case = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files __snake_case = inspect.getsourcefile(_a ) __snake_case = os.path.dirname(_a ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. __snake_case = [os.path.join(_a , _a ) for fn in os.listdir(_a ) if fn.startswith('''modeling_''' )] # Get the source code strings __snake_case = [] for path in modeling_paths: if os.path.isfile(_a ): with open(_a ) as fp: modeling_sources.append(fp.read() ) __snake_case = [] for config_param, default_value in zip(_a , _a ): # `attributes` here is all the variant names for `config_param` __snake_case = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(_a , _a , _a , _a ): unused_attributes.append(attributes[0] ) return sorted(_a ) def lowerCamelCase__ ( ) -> int: __snake_case = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) __snake_case = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda snake_case_ : inspect.isclass(_a ) and issubclass(_a , _a ) and inspect.getmodule(_a ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: __snake_case = check_config_attributes_being_used(_a ) if len(_a ) > 0: __snake_case = unused_attributes if len(_a ) > 0: __snake_case = '''The following configuration classes contain unused attributes in the corresponding modeling files:\n''' for name, attributes in configs_with_unused_attributes.items(): error += f"""{name}: {attributes}\n""" raise ValueError(_a ) if __name__ == "__main__": check_config_attributes()
592
"""simple docstring""" _snake_case = { "Pillow": "Pillow<10.0.0", "accelerate": "accelerate>=0.20.3", "av": "av==9.2.0", "beautifulsoup4": "beautifulsoup4", "black": "black~=23.1", "codecarbon": "codecarbon==1.2.0", "cookiecutter": "cookiecutter==1.7.3", "dataclasses": "dataclasses", "datasets": "datasets!=2.5.0", "decord": "decord==0.6.0", "deepspeed": "deepspeed>=0.9.3", "diffusers": "diffusers", "dill": "dill<0.3.5", "evaluate": "evaluate>=0.2.0", "fairscale": "fairscale>0.3", "faiss-cpu": "faiss-cpu", "fastapi": "fastapi", "filelock": "filelock", "flax": "flax>=0.4.1,<=0.7.0", "ftfy": "ftfy", "fugashi": "fugashi>=1.0", "GitPython": "GitPython<3.1.19", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.14.1,<1.0", "importlib_metadata": "importlib_metadata", "ipadic": "ipadic>=1.0.0,<2.0", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2,<=0.4.13", "jaxlib": "jaxlib>=0.1.65,<=0.4.13", "jieba": "jieba", "kenlm": "kenlm", "keras-nlp": "keras-nlp>=0.3.1", "librosa": "librosa", "nltk": "nltk", "natten": "natten>=0.14.6", "numpy": "numpy>=1.17", "onnxconverter-common": "onnxconverter-common", "onnxruntime-tools": "onnxruntime-tools>=1.4.2", "onnxruntime": "onnxruntime>=1.4.0", "opencv-python": "opencv-python", "optuna": "optuna", "optax": "optax>=0.0.8,<=0.1.4", "packaging": "packaging>=20.0", "parameterized": "parameterized", "phonemizer": "phonemizer", "protobuf": "protobuf", "psutil": "psutil", "pyyaml": "pyyaml>=5.1", "pydantic": "pydantic<2", "pytest": "pytest>=7.2.0", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "python": "python>=3.8.0", "ray[tune]": "ray[tune]", "regex": "regex!=2019.12.17", "requests": "requests", "rhoknp": "rhoknp>=1.1.0,<1.3.1", "rjieba": "rjieba", "rouge-score": "rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1", "ruff": "ruff>=0.0.241,<=0.0.259", "sacrebleu": "sacrebleu>=1.4.12,<2.0.0", "sacremoses": "sacremoses", "safetensors": "safetensors>=0.3.1", "sagemaker": "sagemaker>=2.31.0", "scikit-learn": "scikit-learn", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "sigopt": "sigopt", "starlette": "starlette", "sudachipy": "sudachipy>=0.6.6", "sudachidict_core": "sudachidict_core>=20220729", "tensorflow-cpu": "tensorflow-cpu>=2.6,<2.14", "tensorflow": "tensorflow>=2.6,<2.14", "tensorflow-text": "tensorflow-text<2.14", "tf2onnx": "tf2onnx", "timeout-decorator": "timeout-decorator", "timm": "timm", "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14", "torch": "torch>=1.9,!=1.12.0", "torchaudio": "torchaudio", "torchvision": "torchvision", "pyctcdecode": "pyctcdecode>=0.4.0", "tqdm": "tqdm>=4.27", "unidic": "unidic>=1.0.2", "unidic_lite": "unidic_lite>=1.0.7", "urllib3": "urllib3<2.0.0", "uvicorn": "uvicorn", }
510
0
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class snake_case_ : def __init__( self , __lowercase , __lowercase=1_3 , __lowercase=7 , __lowercase=True , __lowercase=True , __lowercase=False , __lowercase=True , __lowercase=9_9 , __lowercase=3_2 , __lowercase=5 , __lowercase=4 , __lowercase=3_7 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=5_1_2 , __lowercase=1_6 , __lowercase=2 , __lowercase=0.0_2 , __lowercase=3 , __lowercase=4 , __lowercase=None , ) -> Dict: lowerCamelCase : List[Any] =parent lowerCamelCase : Any =batch_size lowerCamelCase : Tuple =seq_length lowerCamelCase : Dict =is_training lowerCamelCase : List[str] =use_input_mask lowerCamelCase : Union[str, Any] =use_token_type_ids lowerCamelCase : Optional[Any] =use_labels lowerCamelCase : List[Any] =vocab_size lowerCamelCase : Optional[int] =hidden_size lowerCamelCase : Optional[Any] =num_hidden_layers lowerCamelCase : Optional[Any] =num_attention_heads lowerCamelCase : str =intermediate_size lowerCamelCase : Any =hidden_act lowerCamelCase : Dict =hidden_dropout_prob lowerCamelCase : Dict =attention_probs_dropout_prob lowerCamelCase : int =max_position_embeddings lowerCamelCase : Optional[Any] =type_vocab_size lowerCamelCase : str =type_sequence_label_size lowerCamelCase : int =initializer_range lowerCamelCase : Union[str, Any] =num_labels lowerCamelCase : Union[str, Any] =num_choices lowerCamelCase : str =scope def __lowercase ( self ) -> List[Any]: lowerCamelCase : Union[str, Any] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCamelCase : List[str] =None if self.use_input_mask: lowerCamelCase : int =random_attention_mask([self.batch_size, self.seq_length] ) lowerCamelCase : List[str] =None if self.use_token_type_ids: lowerCamelCase : int =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCamelCase : str =None lowerCamelCase : List[str] =None lowerCamelCase : List[Any] =None if self.use_labels: lowerCamelCase : Tuple =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase : List[Any] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCamelCase : List[str] =ids_tensor([self.batch_size] , self.num_choices ) lowerCamelCase : List[str] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase ( self ) -> List[str]: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , use_stable_embedding=__lowercase , ) def __lowercase ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> List[str]: lowerCamelCase : str =OpenLlamaModel(config=__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : Optional[Any] =model(__lowercase , attention_mask=__lowercase ) lowerCamelCase : Dict =model(__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ) -> Union[str, Any]: lowerCamelCase : Optional[Any] =True lowerCamelCase : int =OpenLlamaModel(__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : Union[str, Any] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , ) lowerCamelCase : Optional[int] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , ) lowerCamelCase : Optional[int] =model(__lowercase , attention_mask=__lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ) -> str: lowerCamelCase : List[Any] =OpenLlamaForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : str =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , ) -> Dict: lowerCamelCase : Optional[Any] =True lowerCamelCase : Union[str, Any] =True lowerCamelCase : Optional[Any] =OpenLlamaForCausalLM(config=__lowercase ) model.to(__lowercase ) model.eval() # first forward pass lowerCamelCase : List[Any] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , use_cache=__lowercase , ) lowerCamelCase : Union[str, Any] =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCamelCase : Any =ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCamelCase : Any =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCamelCase : Optional[int] =torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCamelCase : Optional[int] =torch.cat([input_mask, next_mask] , dim=-1 ) lowerCamelCase : Optional[Any] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , output_hidden_states=__lowercase , )['''hidden_states'''][0] lowerCamelCase : Optional[int] =model( __lowercase , attention_mask=__lowercase , encoder_hidden_states=__lowercase , encoder_attention_mask=__lowercase , past_key_values=__lowercase , output_hidden_states=__lowercase , )['''hidden_states'''][0] # select random slice lowerCamelCase : Optional[int] =ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCamelCase : Union[str, Any] =output_from_no_past[:, -3:, random_slice_idx].detach() lowerCamelCase : str =output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__lowercase , __lowercase , atol=1e-3 ) ) def __lowercase ( self ) -> Optional[Any]: lowerCamelCase : Tuple =self.prepare_config_and_inputs() ( lowerCamelCase ) : List[Any] =config_and_inputs lowerCamelCase : Tuple ={'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case_ ( _A , _A , _A , unittest.TestCase): lowerCamelCase :Any = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) lowerCamelCase :Union[str, Any] = (OpenLlamaForCausalLM,) if is_torch_available() else () lowerCamelCase :Dict = ( { "feature-extraction": OpenLlamaModel, "text-classification": OpenLlamaForSequenceClassification, "text-generation": OpenLlamaForCausalLM, "zero-shot": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase :int = False lowerCamelCase :Optional[Any] = False def __lowercase ( self ) -> Any: lowerCamelCase : Any =OpenLlamaModelTester(self ) lowerCamelCase : Tuple =ConfigTester(self , config_class=__lowercase , hidden_size=3_7 ) def __lowercase ( self ) -> Optional[int]: self.config_tester.run_common_tests() def __lowercase ( self ) -> Any: lowerCamelCase : Any =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase ) def __lowercase ( self ) -> List[str]: lowerCamelCase : Tuple =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCamelCase : str =type self.model_tester.create_and_check_model(*__lowercase ) def __lowercase ( self ) -> Optional[Any]: lowerCamelCase : int =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase : List[str] =3 lowerCamelCase : Tuple =input_dict['''input_ids'''] lowerCamelCase : Tuple =input_ids.ne(1 ).to(__lowercase ) lowerCamelCase : Optional[Any] =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCamelCase : str =OpenLlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : Optional[int] =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase ( self ) -> Dict: lowerCamelCase : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase : Optional[Any] =3 lowerCamelCase : Union[str, Any] ='''single_label_classification''' lowerCamelCase : List[str] =input_dict['''input_ids'''] lowerCamelCase : Optional[int] =input_ids.ne(1 ).to(__lowercase ) lowerCamelCase : int =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCamelCase : Optional[Any] =OpenLlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : List[Any] =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase ( self ) -> List[Any]: lowerCamelCase : List[Any] =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase : Union[str, Any] =3 lowerCamelCase : Optional[int] ='''multi_label_classification''' lowerCamelCase : Union[str, Any] =input_dict['''input_ids'''] lowerCamelCase : Any =input_ids.ne(1 ).to(__lowercase ) lowerCamelCase : Dict =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCamelCase : int =OpenLlamaForSequenceClassification(__lowercase ) model.to(__lowercase ) model.eval() lowerCamelCase : List[str] =model(__lowercase , attention_mask=__lowercase , labels=__lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test''' ) def __lowercase ( self ) -> Tuple: pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def __lowercase ( self , __lowercase ) -> int: lowerCamelCase : str =self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase : List[str] =ids_tensor([1, 1_0] , config.vocab_size ) lowerCamelCase : List[Any] =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCamelCase : Dict =OpenLlamaModel(__lowercase ) original_model.to(__lowercase ) original_model.eval() lowerCamelCase : Any =original_model(__lowercase ).last_hidden_state lowerCamelCase : Optional[int] =original_model(__lowercase ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCamelCase : Tuple ={'''type''': scaling_type, '''factor''': 1_0.0} lowerCamelCase : List[Any] =OpenLlamaModel(__lowercase ) scaled_model.to(__lowercase ) scaled_model.eval() lowerCamelCase : List[Any] =scaled_model(__lowercase ).last_hidden_state lowerCamelCase : List[Any] =scaled_model(__lowercase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(__lowercase , __lowercase , atol=1e-5 ) )
708
import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def A__ ( SCREAMING_SNAKE_CASE_ ) -> tuple: return (data["data"], data["target"]) def A__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> np.ndarray: lowerCamelCase : Dict =XGBRegressor(verbosity=0 , random_state=4_2 ) xgb.fit(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Predict target for test data lowerCamelCase : List[str] =xgb.predict(SCREAMING_SNAKE_CASE_ ) lowerCamelCase : List[Any] =predictions.reshape(len(SCREAMING_SNAKE_CASE_ ) , 1 ) return predictions def A__ ( ) -> None: lowerCamelCase : Union[str, Any] =fetch_california_housing() lowerCamelCase , lowerCamelCase : Optional[Any] =data_handling(SCREAMING_SNAKE_CASE_ ) lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase : str =train_test_split( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , test_size=0.2_5 , random_state=1 ) lowerCamelCase : str =xgboost(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # Error printing print(F"Mean Absolute Error : {mean_absolute_error(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}" ) print(F"Mean Square Error : {mean_squared_error(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )}" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
262
0
import json import os from typing import Optional, Tuple import regex as re from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { "vocab_file": "vocab.json", "merges_file": "merges.txt", } UpperCamelCase_ = { "vocab_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-vocab.json"}, "merges_file": {"ctrl": "https://raw.githubusercontent.com/salesforce/ctrl/master/ctrl-merges.txt"}, } UpperCamelCase_ = { "ctrl": 2_5_6, } UpperCamelCase_ = { "Pregnancy": 1_6_8_6_2_9, "Christianity": 7_6_7_5, "Explain": 1_0_6_4_2_3, "Fitness": 6_3_4_4_0, "Saving": 6_3_1_6_3, "Ask": 2_7_1_7_1, "Ass": 9_5_9_8_5, "Joke": 1_6_3_5_0_9, "Questions": 4_5_6_2_2, "Thoughts": 4_9_6_0_5, "Retail": 5_2_3_4_2, "Feminism": 1_6_4_3_3_8, "Writing": 1_1_9_9_2, "Atheism": 1_9_2_2_6_3, "Netflix": 4_8_6_1_6, "Computing": 3_9_6_3_9, "Opinion": 4_3_2_1_3, "Alone": 4_4_9_6_7, "Funny": 5_8_9_1_7, "Gaming": 4_0_3_5_8, "Human": 4_0_8_8, "India": 1_3_3_1, "Joker": 7_7_1_3_8, "Diet": 3_6_2_0_6, "Legal": 1_1_8_5_9, "Norman": 4_9_3_9, "Tip": 7_2_6_8_9, "Weight": 5_2_3_4_3, "Movies": 4_6_2_7_3, "Running": 2_3_4_2_5, "Science": 2_0_9_0, "Horror": 3_7_7_9_3, "Confession": 6_0_5_7_2, "Finance": 1_2_2_5_0, "Politics": 1_6_3_6_0, "Scary": 1_9_1_9_8_5, "Support": 1_2_6_5_4, "Technologies": 3_2_5_1_6, "Teenage": 6_6_1_6_0, "Event": 3_2_7_6_9, "Learned": 6_7_4_6_0, "Notion": 1_8_2_7_7_0, "Wikipedia": 3_7_5_8_3, "Books": 6_6_6_5, "Extract": 7_6_0_5_0, "Confessions": 1_0_2_7_0_1, "Conspiracy": 7_5_9_3_2, "Links": 6_3_6_7_4, "Narcissus": 1_5_0_4_2_5, "Relationship": 5_4_7_6_6, "Relationships": 1_3_4_7_9_6, "Reviews": 4_1_6_7_1, "News": 4_2_5_6, "Translation": 2_6_8_2_0, "multilingual": 1_2_8_4_0_6, } def _UpperCAmelCase ( UpperCamelCase: Optional[Any] ): """simple docstring""" __lowerCAmelCase = set() __lowerCAmelCase = word[0] for char in word[1:]: pairs.add((prev_char, char) ) __lowerCAmelCase = char __lowerCAmelCase = set(UpperCamelCase ) return pairs class a ( __UpperCAmelCase ): lowercase_ : str = VOCAB_FILES_NAMES lowercase_ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP lowercase_ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ : Dict = CONTROL_CODES def __init__( self : Dict , snake_case__ : List[str] , snake_case__ : List[str] , snake_case__ : List[Any]="<unk>" , **snake_case__ : Dict ): """simple docstring""" super().__init__(unk_token=snake_case__ , **snake_case__ ) with open(snake_case__ , encoding="utf-8" ) as vocab_handle: __lowerCAmelCase = json.load(snake_case__ ) __lowerCAmelCase = {v: k for k, v in self.encoder.items()} with open(snake_case__ , encoding="utf-8" ) as merges_handle: __lowerCAmelCase = merges_handle.read().split("\n" )[1:-1] __lowerCAmelCase = [tuple(merge.split() ) for merge in merges] __lowerCAmelCase = dict(zip(snake_case__ , range(len(snake_case__ ) ) ) ) __lowerCAmelCase = {} @property def UpperCAmelCase__ ( self : Any ): """simple docstring""" return len(self.encoder ) def UpperCAmelCase__ ( self : int ): """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : Optional[int] , snake_case__ : List[str] ): """simple docstring""" if token in self.cache: return self.cache[token] __lowerCAmelCase = tuple(snake_case__ ) __lowerCAmelCase = tuple(list(word[:-1] ) + [word[-1] + "</w>"] ) __lowerCAmelCase = get_pairs(snake_case__ ) if not pairs: return token while True: __lowerCAmelCase = min(snake_case__ , key=lambda snake_case__ : self.bpe_ranks.get(snake_case__ , float("inf" ) ) ) if bigram not in self.bpe_ranks: break __lowerCAmelCase , __lowerCAmelCase = bigram __lowerCAmelCase = [] __lowerCAmelCase = 0 while i < len(snake_case__ ): try: __lowerCAmelCase = word.index(snake_case__ , snake_case__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) __lowerCAmelCase = j if word[i] == first and i < len(snake_case__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 __lowerCAmelCase = tuple(snake_case__ ) __lowerCAmelCase = new_word if len(snake_case__ ) == 1: break else: __lowerCAmelCase = get_pairs(snake_case__ ) __lowerCAmelCase = "@@ ".join(snake_case__ ) __lowerCAmelCase = word[:-4] __lowerCAmelCase = word return word def UpperCAmelCase__ ( self : Union[str, Any] , snake_case__ : Tuple ): """simple docstring""" __lowerCAmelCase = [] __lowerCAmelCase = re.findall(R"\S+\n?" , snake_case__ ) for token in words: split_tokens.extend(list(self.bpe(snake_case__ ).split(" " ) ) ) return split_tokens def UpperCAmelCase__ ( self : int , snake_case__ : List[str] ): """simple docstring""" return self.encoder.get(snake_case__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Any , snake_case__ : int ): """simple docstring""" return self.decoder.get(snake_case__ , self.unk_token ) def UpperCAmelCase__ ( self : Tuple , snake_case__ : List[str] ): """simple docstring""" __lowerCAmelCase = " ".join(snake_case__ ).replace("@@ " , "" ).strip() return out_string def UpperCAmelCase__ ( self : Optional[int] , snake_case__ : str , snake_case__ : Optional[str] = None ): """simple docstring""" if not os.path.isdir(snake_case__ ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return __lowerCAmelCase = os.path.join( snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) __lowerCAmelCase = os.path.join( snake_case__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"] ) with open(snake_case__ , "w" , encoding="utf-8" ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=snake_case__ , ensure_ascii=snake_case__ ) + "\n" ) __lowerCAmelCase = 0 with open(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 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!" ) __lowerCAmelCase = token_index writer.write(" ".join(snake_case__ ) + "\n" ) index += 1 return vocab_file, merge_file # def decode(self, token_ids, skip_special_tokens=False, clean_up_tokenization_spaces=True): # filtered_tokens = ' '.join(self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)) # tokens_generated_so_far = re.sub('(@@ )', '', string=filtered_tokens) # tokens_generated_so_far = re.sub('(@@ ?$)', '', string=tokens_generated_so_far) # return ''.join(tokens_generated_so_far)
611
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class a ( __UpperCAmelCase ): lowercase_ : Optional[int] = 'layoutlmv3' def __init__( self : Dict , snake_case__ : Dict=50_265 , snake_case__ : Optional[Any]=768 , snake_case__ : Dict=12 , snake_case__ : List[Any]=12 , snake_case__ : int=3_072 , snake_case__ : Dict="gelu" , snake_case__ : Any=0.1 , snake_case__ : Optional[Any]=0.1 , snake_case__ : Tuple=512 , snake_case__ : str=2 , snake_case__ : Optional[int]=0.0_2 , snake_case__ : Optional[Any]=1E-5 , snake_case__ : Tuple=1 , snake_case__ : str=0 , snake_case__ : Dict=2 , snake_case__ : int=1_024 , snake_case__ : Optional[Any]=128 , snake_case__ : List[str]=128 , snake_case__ : Dict=True , snake_case__ : Optional[int]=32 , snake_case__ : str=128 , snake_case__ : Dict=64 , snake_case__ : Any=256 , snake_case__ : Union[str, Any]=True , snake_case__ : Union[str, Any]=True , snake_case__ : Tuple=True , snake_case__ : List[Any]=224 , snake_case__ : str=3 , snake_case__ : Dict=16 , snake_case__ : Tuple=None , **snake_case__ : Any , ): """simple docstring""" super().__init__( vocab_size=snake_case__ , hidden_size=snake_case__ , num_hidden_layers=snake_case__ , num_attention_heads=snake_case__ , intermediate_size=snake_case__ , hidden_act=snake_case__ , hidden_dropout_prob=snake_case__ , attention_probs_dropout_prob=snake_case__ , max_position_embeddings=snake_case__ , type_vocab_size=snake_case__ , initializer_range=snake_case__ , layer_norm_eps=snake_case__ , pad_token_id=snake_case__ , bos_token_id=snake_case__ , eos_token_id=snake_case__ , **snake_case__ , ) __lowerCAmelCase = max_ad_position_embeddings __lowerCAmelCase = coordinate_size __lowerCAmelCase = shape_size __lowerCAmelCase = has_relative_attention_bias __lowerCAmelCase = rel_pos_bins __lowerCAmelCase = max_rel_pos __lowerCAmelCase = has_spatial_attention_bias __lowerCAmelCase = rel_ad_pos_bins __lowerCAmelCase = max_rel_ad_pos __lowerCAmelCase = text_embed __lowerCAmelCase = visual_embed __lowerCAmelCase = input_size __lowerCAmelCase = num_channels __lowerCAmelCase = patch_size __lowerCAmelCase = classifier_dropout class a ( __UpperCAmelCase ): lowercase_ : int = version.parse('1.12' ) @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) else: return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("bbox", {0: "batch", 1: "sequence"}), ("attention_mask", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels"}), ] ) @property def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" return 1E-5 @property def UpperCAmelCase__ ( self : List[str] ): """simple docstring""" return 12 def UpperCAmelCase__ ( self : Dict , snake_case__ : "ProcessorMixin" , snake_case__ : int = -1 , snake_case__ : int = -1 , snake_case__ : bool = False , snake_case__ : Optional["TensorType"] = None , snake_case__ : int = 3 , snake_case__ : int = 40 , snake_case__ : int = 40 , ): """simple docstring""" setattr(processor.image_processor , "apply_ocr" , snake_case__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowerCAmelCase = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __lowerCAmelCase = processor.tokenizer.num_special_tokens_to_add(snake_case__ ) __lowerCAmelCase = compute_effective_axis_dimension( snake_case__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=snake_case__ ) # Generate dummy inputs according to compute batch and sequence __lowerCAmelCase = [[" ".join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes __lowerCAmelCase = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) __lowerCAmelCase = self._generate_dummy_images(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) __lowerCAmelCase = dict( processor( snake_case__ , text=snake_case__ , boxes=snake_case__ , return_tensors=snake_case__ , ) ) return inputs
611
1
import math def __UpperCamelCase ( ) ->None: """simple docstring""" lowerCamelCase_ =input("""Enter message: """ ) lowerCamelCase_ =int(input(f'Enter key [2-{len(_A ) - 1}]: ' ) ) lowerCamelCase_ =input("""Encryption/Decryption [e/d]: """ ) if mode.lower().startswith("""e""" ): lowerCamelCase_ =encrypt_message(_A , _A ) elif mode.lower().startswith("""d""" ): lowerCamelCase_ =decrypt_message(_A , _A ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f'Output:\n{text + "|"}' ) def __UpperCamelCase ( _A : int , _A : str ) ->str: """simple docstring""" lowerCamelCase_ =[""""""] * key for col in range(_A ): lowerCamelCase_ =col while pointer < len(_A ): cipher_text[col] += message[pointer] pointer += key return "".join(_A ) def __UpperCamelCase ( _A : int , _A : str ) ->str: """simple docstring""" lowerCamelCase_ =math.ceil(len(_A ) / key ) lowerCamelCase_ =key lowerCamelCase_ =(num_cols * num_rows) - len(_A ) lowerCamelCase_ =[""""""] * num_cols lowerCamelCase_ =0 lowerCamelCase_ =0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowerCamelCase_ =0 row += 1 return "".join(_A ) if __name__ == "__main__": import doctest doctest.testmod() main()
706
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class _SCREAMING_SNAKE_CASE ( unittest.TestCase): def _snake_case ( self )-> List[str]: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) self.assertTrue(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , torch_builtin(_SCREAMING_SNAKE_CASE ) ) ) self.assertFalse(torch.allclose(gelu_python(_SCREAMING_SNAKE_CASE ) , gelu_new(_SCREAMING_SNAKE_CASE ) ) ) def _snake_case ( self )-> int: lowerCamelCase_ =torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =get_activation("""gelu_10""" ) lowerCamelCase_ =torch_builtin(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =geluaa(_SCREAMING_SNAKE_CASE ) lowerCamelCase_ =torch.where(y_gelu_aa < 1_0.0 , 1 , 0 ) self.assertTrue(torch.max(_SCREAMING_SNAKE_CASE ).item() == 1_0.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def _snake_case ( self )-> Dict: get_activation("""gelu""" ) get_activation("""gelu_10""" ) get_activation("""gelu_fast""" ) get_activation("""gelu_new""" ) get_activation("""gelu_python""" ) get_activation("""gelu_pytorch_tanh""" ) get_activation("""linear""" ) get_activation("""mish""" ) get_activation("""quick_gelu""" ) get_activation("""relu""" ) get_activation("""sigmoid""" ) get_activation("""silu""" ) get_activation("""swish""" ) get_activation("""tanh""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation("""bogus""" ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): get_activation(_SCREAMING_SNAKE_CASE ) def _snake_case ( self )-> Any: lowerCamelCase_ =get_activation("""gelu""" ) lowerCamelCase_ =1 lowerCamelCase_ =get_activation("""gelu""" ) self.assertEqual(acta.a , 1 ) with self.assertRaises(_SCREAMING_SNAKE_CASE ): lowerCamelCase_ =acta.a
75
0
'''simple docstring''' from manim import * class SCREAMING_SNAKE_CASE_ ( snake_case ): def _snake_case ( self ) -> Dict: '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = Rectangle(height=0.5 , width=0.5 ) __SCREAMING_SNAKE_CASE : int = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = Rectangle(height=0.2_5 , width=0.2_5 ) __SCREAMING_SNAKE_CASE : Dict = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE : Union[str, Any] = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE : Optional[Any] = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : List[Any] = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : List[str] = VGroup(lowercase , lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : List[str] = Text('''CPU''' , font_size=2_4 ) __SCREAMING_SNAKE_CASE : int = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) cpu.move_to([-2.5, -0.5, 0] ) self.add(lowercase ) __SCREAMING_SNAKE_CASE : List[Any] = [mem.copy() for i in range(4 )] __SCREAMING_SNAKE_CASE : Union[str, Any] = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = Text('''GPU''' , font_size=2_4 ) __SCREAMING_SNAKE_CASE : Any = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) gpu.move_to([-1, -1, 0] ) self.add(lowercase ) __SCREAMING_SNAKE_CASE : Any = [mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE : str = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : List[Any] = Text('''Model''' , font_size=2_4 ) __SCREAMING_SNAKE_CASE : str = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) model.move_to([3, -1.0, 0] ) self.add(lowercase ) __SCREAMING_SNAKE_CASE : Dict = [] __SCREAMING_SNAKE_CASE : Dict = [] for i, rect in enumerate(lowercase ): __SCREAMING_SNAKE_CASE : Optional[Any] = fill.copy().set_fill(lowercase , opacity=0.8 ) target.move_to(lowercase ) model_arr.append(lowercase ) __SCREAMING_SNAKE_CASE : List[Any] = Rectangle(height=0.4_6 , width=0.4_6 ).set_stroke(width=0.0 ).set_fill(lowercase , opacity=0.8 ) cpu_target.move_to(cpu_left_col_base[i] ) model_cpu_arr.append(lowercase ) self.add(*lowercase , *lowercase ) __SCREAMING_SNAKE_CASE : List[Any] = [meta_mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE : List[str] = [meta_mem.copy() for i in range(6 )] __SCREAMING_SNAKE_CASE : int = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : List[Any] = VGroup(*lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : Optional[Any] = VGroup(lowercase , lowercase ).arrange(lowercase , buff=0 ) __SCREAMING_SNAKE_CASE : Tuple = Text('''Disk''' , font_size=2_4 ) __SCREAMING_SNAKE_CASE : List[Any] = Group(lowercase , lowercase ).arrange(lowercase , buff=0.5 , aligned_edge=lowercase ) disk.move_to([-4, -1.2_5, 0] ) self.add(lowercase , lowercase ) __SCREAMING_SNAKE_CASE : str = Square(side_length=2.2 ) key.move_to([-5, 2, 0] ) __SCREAMING_SNAKE_CASE : List[Any] = MarkupText( f"""<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model""" , font_size=1_8 , ) key_text.move_to([-5, 2.4, 0] ) self.add(lowercase , lowercase ) __SCREAMING_SNAKE_CASE : Dict = MarkupText( f"""<span fgcolor='{BLUE}'>●</span> Checkpoint""" , font_size=1_8 , ) blue_text.next_to(lowercase , DOWN * 2.4 , aligned_edge=key_text.get_left() ) self.add(lowercase ) __SCREAMING_SNAKE_CASE : str = MarkupText( f"""Now watch as an input is passed through the model\nand how the memory is utilized and handled.""" , font_size=2_4 , ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase ) ) __SCREAMING_SNAKE_CASE : Tuple = Square(0.3 ) input.set_fill(lowercase , opacity=1.0 ) input.set_stroke(width=0.0 ) input.next_to(model_base[0] , lowercase , buff=0.5 ) self.play(Write(lowercase ) ) input.generate_target() input.target.next_to(model_arr[0] , direction=lowercase , buff=0.0_2 ) self.play(MoveToTarget(lowercase ) ) self.play(FadeOut(lowercase ) ) __SCREAMING_SNAKE_CASE : List[Any] = Arrow(start=lowercase , end=lowercase , color=lowercase , buff=0.5 ) a.next_to(model_arr[0].get_left() , lowercase , buff=0.2 ) model_cpu_arr[0].generate_target() model_cpu_arr[0].target.move_to(gpu_rect[0] ) __SCREAMING_SNAKE_CASE : Any = MarkupText( f"""As the input reaches a layer, the hook triggers\nand weights are moved from the CPU\nto the GPU and back.""" , font_size=2_4 , ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase , run_time=3 ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''run_time''': 1, '''fade_in''': True, '''fade_out''': True, '''buff''': 0.0_2} self.play( Write(lowercase ) , Circumscribe(model_arr[0] , color=lowercase , **lowercase ) , Circumscribe(model_cpu_arr[0] , color=lowercase , **lowercase ) , Circumscribe(gpu_rect[0] , color=lowercase , **lowercase ) , ) self.play(MoveToTarget(model_cpu_arr[0] ) ) __SCREAMING_SNAKE_CASE : Dict = a.copy() for i in range(6 ): a_c.next_to(model_arr[i].get_right() + 0.0_2 , lowercase , buff=0.2 ) input.generate_target() input.target.move_to(model_arr[i].get_right() + 0.0_2 ) __SCREAMING_SNAKE_CASE : Optional[int] = AnimationGroup( FadeOut(lowercase , run_time=0.5 ) , MoveToTarget(lowercase , run_time=0.5 ) , FadeIn(lowercase , run_time=0.5 ) , lag_ratio=0.2 ) self.play(lowercase ) model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[i] ) if i < 5: model_cpu_arr[i + 1].generate_target() model_cpu_arr[i + 1].target.move_to(gpu_rect[0] ) if i >= 1: __SCREAMING_SNAKE_CASE : int = 0.7 self.play( Circumscribe(model_arr[i] , **lowercase ) , Circumscribe(cpu_left_col_base[i] , **lowercase ) , Circumscribe(cpu_left_col_base[i + 1] , color=lowercase , **lowercase ) , Circumscribe(gpu_rect[0] , color=lowercase , **lowercase ) , Circumscribe(model_arr[i + 1] , color=lowercase , **lowercase ) , ) if i < 1: self.play( MoveToTarget(model_cpu_arr[i] ) , MoveToTarget(model_cpu_arr[i + 1] ) , ) else: self.play( MoveToTarget(model_cpu_arr[i] , run_time=0.7 ) , MoveToTarget(model_cpu_arr[i + 1] , run_time=0.7 ) , ) else: model_cpu_arr[i].generate_target() model_cpu_arr[i].target.move_to(cpu_left_col_base[-1] ) input.generate_target() input.target.next_to(model_arr[-1].get_right() , RIGHT + 0.0_2 , buff=0.2 ) self.play( Circumscribe(model_arr[-1] , color=lowercase , **lowercase ) , Circumscribe(cpu_left_col_base[-1] , color=lowercase , **lowercase ) , Circumscribe(gpu_rect[0] , color=lowercase , **lowercase ) , ) self.play(MoveToTarget(model_cpu_arr[i] ) ) __SCREAMING_SNAKE_CASE : int = a_c __SCREAMING_SNAKE_CASE : Optional[Any] = a_c.copy() input.generate_target() input.target.next_to(model_base[-1] , RIGHT + 0.0_2 , buff=0.5 ) self.play( FadeOut(lowercase ) , FadeOut(lowercase , run_time=0.5 ) , ) __SCREAMING_SNAKE_CASE : Dict = MarkupText(f"""Inference on a model too large for GPU memory\nis successfully completed.""" , font_size=2_4 ) step_a.move_to([2, 2, 0] ) self.play(Write(lowercase , run_time=3 ) , MoveToTarget(lowercase ) ) self.wait()
158
'''simple docstring''' import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params _A = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ["""memory_attention""", """encoder_attn"""], ["""attention""", """attn"""], ["""/""", """."""], [""".LayerNorm.gamma""", """_layer_norm.weight"""], [""".LayerNorm.beta""", """_layer_norm.bias"""], ["""r.layer_""", """r.layers."""], ["""output_proj""", """out_proj"""], ["""ffn.dense_1.""", """fc2."""], ["""ffn.dense.""", """fc1."""], ["""ffn_layer_norm""", """final_layer_norm"""], ["""kernel""", """weight"""], ["""encoder_layer_norm.""", """encoder.layer_norm."""], ["""decoder_layer_norm.""", """decoder.layer_norm."""], ["""embeddings.weights""", """shared.weight"""], ] def A_ ( __SCREAMING_SNAKE_CASE : Dict ) -> List[Any]: for pegasus_name, hf_name in PATTERNS: __SCREAMING_SNAKE_CASE : List[str] = k.replace(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return k def A_ ( __SCREAMING_SNAKE_CASE : dict , __SCREAMING_SNAKE_CASE : dict ) -> PegasusForConditionalGeneration: __SCREAMING_SNAKE_CASE : Tuple = DEFAULTS.copy() cfg_kwargs.update(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Union[str, Any] = PegasusConfig(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = PegasusForConditionalGeneration(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Tuple = torch_model.model.state_dict() __SCREAMING_SNAKE_CASE : Dict = {} for k, v in tf_weights.items(): __SCREAMING_SNAKE_CASE : List[str] = rename_state_dict_key(__SCREAMING_SNAKE_CASE ) if new_k not in sd: raise ValueError(f"""could not find new key {new_k} in state dict. (converted from {k})""" ) if "dense" in k or "proj" in new_k: __SCREAMING_SNAKE_CASE : Dict = v.T __SCREAMING_SNAKE_CASE : Any = torch.tensor(__SCREAMING_SNAKE_CASE , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, f"""{new_k}, {k}, {v.shape}, {sd[new_k].shape}""" # make sure embedding.padding_idx is respected __SCREAMING_SNAKE_CASE : int = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1] ) __SCREAMING_SNAKE_CASE : Optional[Any] = mapping['''shared.weight'''] __SCREAMING_SNAKE_CASE : Tuple = mapping['''shared.weight'''] __SCREAMING_SNAKE_CASE : List[Any] = {k: torch.zeros_like(__SCREAMING_SNAKE_CASE ) for k, v in sd.items() if k.endswith('''bias''' ) and k not in mapping} mapping.update(**__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = torch_model.model.load_state_dict(__SCREAMING_SNAKE_CASE , strict=__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = [ k for k in missing if k not in ['''encoder.embed_positions.weight''', '''decoder.embed_positions.weight'''] ] assert unexpected_missing == [], f"""no matches found for the following torch keys {unexpected_missing}""" assert extra == [], f"""no matches found for the following tf keys {extra}""" return torch_model def A_ ( __SCREAMING_SNAKE_CASE : Union[str, Any]="./ckpt/aeslc/model.ckpt-32000" ) -> Dict: __SCREAMING_SNAKE_CASE : Any = tf.train.list_variables(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''Adafactor''', '''global_step'''] for name, shape in tqdm(__SCREAMING_SNAKE_CASE , desc='''converting tf checkpoint to dict''' ): __SCREAMING_SNAKE_CASE : Tuple = any(pat in name for pat in ignore_name ) if skip_key: continue __SCREAMING_SNAKE_CASE : Any = tf.train.load_variable(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : Dict = array return tf_weights def A_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ) -> Optional[int]: # save tokenizer first __SCREAMING_SNAKE_CASE : List[str] = Path(__SCREAMING_SNAKE_CASE ).parent.name __SCREAMING_SNAKE_CASE : Optional[int] = task_specific_params[f"""summarization_{dataset}"""]['''max_position_embeddings'''] __SCREAMING_SNAKE_CASE : List[str] = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=__SCREAMING_SNAKE_CASE ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(__SCREAMING_SNAKE_CASE ) # convert model __SCREAMING_SNAKE_CASE : Any = get_tf_weights_as_numpy(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : str = task_specific_params[f"""summarization_{dataset}"""] if dataset == "large": __SCREAMING_SNAKE_CASE : Dict = task_specific_params __SCREAMING_SNAKE_CASE : Optional[int] = convert_pegasus(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) torch_model.save_pretrained(__SCREAMING_SNAKE_CASE ) __SCREAMING_SNAKE_CASE : List[Any] = torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''' ) sd.pop('''model.encoder.embed_positions.weight''' ) torch.save(__SCREAMING_SNAKE_CASE , Path(__SCREAMING_SNAKE_CASE ) / '''pytorch_model.bin''' ) if __name__ == "__main__": _A = argparse.ArgumentParser() # Required parameters parser.add_argument("""tf_ckpt_path""", type=str, help="""passed to tf.train.list_variables""") parser.add_argument("""save_dir""", default=None, type=str, help="""Path to the output PyTorch model.""") _A = parser.parse_args() if args.save_dir is None: _A = Path(args.tf_ckpt_path).parent.name _A = os.path.join("""pegasus""", dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
158
1
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 SCREAMING_SNAKE_CASE__ : str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = XLMRobertaTokenizer lowercase_ = XLMRobertaTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaTokenizer(a_ , keep_accents=a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = '<pad>' SCREAMING_SNAKE_CASE__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 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(a_ ) , 1002 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaTokenizer(a_ , keep_accents=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize('This is a test' ) self.assertListEqual(a_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( a_ , [ 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', 'é', '.', ] , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_tokens_to_ids(a_ ) self.assertListEqual( a_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.convert_ids_to_tokens(a_ ) self.assertListEqual( a_ , [ 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 __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" 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 SCREAMING_SNAKE_CASE__ : Union[str, 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})''' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer_class.from_pretrained(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Any = tokenizer_r.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_p.save_pretrained(a_ ) # 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 ) ) SCREAMING_SNAKE_CASE__ : List[str] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(a_ , a_ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(a_ ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Any = tokenizer_r.save_pretrained(a_ , legacy_format=a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer_p.save_pretrained(a_ ) # Checks it save with the same files self.assertSequenceEqual(a_ , a_ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) shutil.rmtree(a_ ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_r.save_pretrained(a_ , legacy_format=a_ ) SCREAMING_SNAKE_CASE__ : int = tokenizer_p.save_pretrained(a_ ) # 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 SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) shutil.rmtree(a_ ) @cached_property def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a_ , f.name ) SCREAMING_SNAKE_CASE__ : int = XLMRobertaTokenizer(f.name , keep_accents=a_ ) SCREAMING_SNAKE_CASE__ : Dict = pickle.dumps(a_ ) pickle.loads(a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : int = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'Hello World!' SCREAMING_SNAKE_CASE__ : List[Any] = [0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ( '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' ) SCREAMING_SNAKE_CASE__ : List[str] = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 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, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = {'input_ids': [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 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, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 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=a_ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
700
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available __a :List[Any] = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a :Dict = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a :List[str] = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys __a :str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
86
'''simple docstring''' def UpperCamelCase__ ( lowerCAmelCase ): """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 _lowerCAmelCase = 1 _lowerCAmelCase = 1 while repunit: _lowerCAmelCase = (10 * repunit + 1) % divisor repunit_index += 1 return repunit_index def UpperCamelCase__ ( lowerCAmelCase = 1_00_00_00 ): """simple docstring""" _lowerCAmelCase = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(lowerCAmelCase ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F"""{solution() = }""")
207
0
"""simple docstring""" import math def snake_case ( _a: list , _a: int = 0 , _a: int = 0 )-> list: '''simple docstring''' lowerCamelCase__ = end or len(_a ) for i in range(_a , _a ): lowerCamelCase__ = i lowerCamelCase__ = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: lowerCamelCase__ = array[temp_index - 1] temp_index -= 1 lowerCamelCase__ = temp_index_value return array def snake_case ( _a: list , _a: int , _a: int )-> None: # Max Heap '''simple docstring''' lowerCamelCase__ = index lowerCamelCase__ = 2 * index + 1 # Left Node lowerCamelCase__ = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: lowerCamelCase__ = left_index if right_index < heap_size and array[largest] < array[right_index]: lowerCamelCase__ = right_index if largest != index: lowerCamelCase__ , lowerCamelCase__ = array[largest], array[index] heapify(_a , _a , _a ) def snake_case ( _a: list )-> list: '''simple docstring''' lowerCamelCase__ = len(_a ) for i in range(n // 2 , -1 , -1 ): heapify(_a , _a , _a ) for i in range(n - 1 , 0 , -1 ): lowerCamelCase__ , lowerCamelCase__ = array[0], array[i] heapify(_a , 0 , _a ) return array def snake_case ( _a: list , _a: int , _a: int , _a: int )-> int: '''simple docstring''' if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def snake_case ( _a: list , _a: int , _a: int , _a: int )-> int: '''simple docstring''' lowerCamelCase__ = low lowerCamelCase__ = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i lowerCamelCase__ , lowerCamelCase__ = array[j], array[i] i += 1 def snake_case ( _a: list )-> list: '''simple docstring''' if len(_a ) == 0: return array lowerCamelCase__ = 2 * math.ceil(math.loga(len(_a ) ) ) lowerCamelCase__ = 16 return intro_sort(_a , 0 , len(_a ) , _a , _a ) def snake_case ( _a: list , _a: int , _a: int , _a: int , _a: int )-> list: '''simple docstring''' while end - start > size_threshold: if max_depth == 0: return heap_sort(_a ) max_depth -= 1 lowerCamelCase__ = median_of_a(_a , _a , start + ((end - start) // 2) + 1 , end - 1 ) lowerCamelCase__ = partition(_a , _a , _a , _a ) intro_sort(_a , _a , _a , _a , _a ) lowerCamelCase__ = p return insertion_sort(_a , _a , _a ) if __name__ == "__main__": import doctest doctest.testmod() _snake_case = input("Enter numbers separated by a comma : ").strip() _snake_case = [float(item) for item in user_input.split(",")] print(sort(unsorted))
659
"""simple docstring""" def snake_case ( _a: List[Any] , _a: Any , _a: str , _a: List[Any] )-> List[Any]: '''simple docstring''' lowerCamelCase__ = [False] * len(_a ) lowerCamelCase__ = [] queue.append(_a ) lowerCamelCase__ = True while queue: lowerCamelCase__ = queue.pop(0 ) for ind in range(len(graph[u] ) ): if visited[ind] is False and graph[u][ind] > 0: queue.append(_a ) lowerCamelCase__ = True lowerCamelCase__ = u return visited[t] def snake_case ( _a: List[Any] , _a: str , _a: List[str] )-> Optional[int]: '''simple docstring''' lowerCamelCase__ = [-1] * (len(_a )) lowerCamelCase__ = 0 while bfs(_a , _a , _a , _a ): lowerCamelCase__ = float('Inf' ) lowerCamelCase__ = sink while s != source: # Find the minimum value in select path lowerCamelCase__ = min(_a , graph[parent[s]][s] ) lowerCamelCase__ = parent[s] max_flow += path_flow lowerCamelCase__ = sink while v != source: lowerCamelCase__ = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow lowerCamelCase__ = parent[v] return max_flow _snake_case = [ [0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0], ] _snake_case , _snake_case = 0, 5 print(ford_fulkerson(graph, source, sink))
659
1
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class SCREAMING_SNAKE_CASE ( unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : Any ) -> List[Any]: """simple docstring""" __lowerCAmelCase : List[str] = tempfile.mkdtemp() __lowerCAmelCase : Tuple = [ """[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """的""", """价""", """格""", """是""", """15""", """便""", """alex""", """##andra""", """,""", """。""", """-""", """t""", """shirt""", ] __lowerCAmelCase : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) __lowerCAmelCase : str = { """do_resize""": True, """size""": {"""height""": 2_24, """width""": 2_24}, """do_center_crop""": True, """crop_size""": {"""height""": 18, """width""": 18}, """do_normalize""": True, """image_mean""": [0.4814_5466, 0.457_8275, 0.4082_1073], """image_std""": [0.2686_2954, 0.2613_0258, 0.2757_7711], """do_convert_rgb""": True, } __lowerCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , lowerCAmelCase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(lowerCAmelCase , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , **lowerCAmelCase : Dict ) -> Union[str, Any]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict , **lowerCAmelCase : Any ) -> List[str]: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : int , **lowerCAmelCase : Tuple ) -> List[str]: """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[str] = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )] __lowerCAmelCase : Any = [Image.fromarray(np.moveaxis(lowerCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : Optional[int] = self.get_rust_tokenizer() __lowerCAmelCase : int = self.get_image_processor() __lowerCAmelCase : Any = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) __lowerCAmelCase : Tuple = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowerCAmelCase ) __lowerCAmelCase : Any = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) __lowerCAmelCase : Union[str, Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowerCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , lowerCAmelCase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowerCAmelCase ) self.assertIsInstance(processor_fast.image_processor , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Dict: """simple docstring""" __lowerCAmelCase : str = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __lowerCAmelCase : Optional[Any] = self.get_tokenizer(cls_token="""(CLS)""" , sep_token="""(SEP)""" ) __lowerCAmelCase : str = self.get_image_processor(do_normalize=lowerCAmelCase ) __lowerCAmelCase : List[Any] = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token="""(CLS)""" , sep_token="""(SEP)""" , do_normalize=lowerCAmelCase ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: """simple docstring""" __lowerCAmelCase : Tuple = self.get_image_processor() __lowerCAmelCase : Optional[Any] = self.get_tokenizer() __lowerCAmelCase : Dict = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) __lowerCAmelCase : Optional[int] = self.prepare_image_inputs() __lowerCAmelCase : List[Any] = image_processor(lowerCAmelCase , return_tensors="""np""" ) __lowerCAmelCase : Optional[Any] = processor(images=lowerCAmelCase , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple: """simple docstring""" __lowerCAmelCase : Dict = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : str = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) __lowerCAmelCase : Any = """Alexandra,T-shirt的价格是15便士。""" __lowerCAmelCase : Optional[Any] = processor(text=lowerCAmelCase ) __lowerCAmelCase : Dict = tokenizer(lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Tuple: """simple docstring""" __lowerCAmelCase : List[str] = self.get_image_processor() __lowerCAmelCase : str = self.get_tokenizer() __lowerCAmelCase : int = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) __lowerCAmelCase : Optional[Any] = """Alexandra,T-shirt的价格是15便士。""" __lowerCAmelCase : Tuple = self.prepare_image_inputs() __lowerCAmelCase : List[Any] = processor(text=lowerCAmelCase , images=lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowerCAmelCase ): processor() def SCREAMING_SNAKE_CASE ( self : int ) -> List[Any]: """simple docstring""" __lowerCAmelCase : Any = self.get_image_processor() __lowerCAmelCase : Union[str, Any] = self.get_tokenizer() __lowerCAmelCase : Optional[Any] = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) __lowerCAmelCase : Optional[int] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __lowerCAmelCase : List[Any] = processor.batch_decode(lowerCAmelCase ) __lowerCAmelCase : List[str] = tokenizer.batch_decode(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[Any]: """simple docstring""" __lowerCAmelCase : List[Any] = self.get_image_processor() __lowerCAmelCase : Any = self.get_tokenizer() __lowerCAmelCase : str = ChineseCLIPProcessor(tokenizer=lowerCAmelCase , image_processor=lowerCAmelCase ) __lowerCAmelCase : List[str] = """Alexandra,T-shirt的价格是15便士。""" __lowerCAmelCase : Union[str, Any] = self.prepare_image_inputs() __lowerCAmelCase : Tuple = processor(text=lowerCAmelCase , images=lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
651
from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowerCamelCase : Optional[int] ="" lowerCamelCase : Dict ="hf-legacy" # "hf://"" is reserved for hffs def __init__( self : int , lowerCAmelCase : Optional[DatasetInfo] = None , lowerCAmelCase : Optional[str] = None , **lowerCAmelCase : Optional[Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(self , **lowerCAmelCase ) __lowerCAmelCase : int = repo_info __lowerCAmelCase : Any = token __lowerCAmelCase : int = None def SCREAMING_SNAKE_CASE ( self : Dict ) -> Any: """simple docstring""" if self.dir_cache is None: __lowerCAmelCase : List[Any] = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes __lowerCAmelCase : int = { """name""": hf_file.rfilename, """size""": None, """type""": """file""", } self.dir_cache.update( { str(lowerCAmelCase ): {"""name""": str(lowerCAmelCase ), """size""": None, """type""": """directory"""} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def SCREAMING_SNAKE_CASE ( self : Any , lowerCAmelCase : str , lowerCAmelCase : str = "rb" , **lowerCAmelCase : List[str] , ) -> Any: """simple docstring""" if not isinstance(self.repo_info , lowerCAmelCase ): raise NotImplementedError(f'''Open is only implemented for dataset repositories, but got {self.repo_info}''' ) __lowerCAmelCase : str = hf_hub_url(self.repo_info.id , lowerCAmelCase , revision=self.repo_info.sha ) return fsspec.open( lowerCAmelCase , mode=lowerCAmelCase , headers=get_authentication_headers_for_url(lowerCAmelCase , use_auth_token=self.token ) , client_kwargs={"""trust_env""": True} , ).open() def SCREAMING_SNAKE_CASE ( self : List[Any] , lowerCAmelCase : Union[str, Any] , **lowerCAmelCase : int ) -> Optional[int]: """simple docstring""" self._get_dirs() __lowerCAmelCase : List[Any] = self._strip_protocol(lowerCAmelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] , lowerCAmelCase : Union[str, Any] , lowerCAmelCase : Any=False , **lowerCAmelCase : Any ) -> Optional[Any]: """simple docstring""" self._get_dirs() __lowerCAmelCase : Optional[int] = PurePosixPath(path.strip("""/""" ) ) __lowerCAmelCase : str = {} for p, f in self.dir_cache.items(): __lowerCAmelCase : Optional[Any] = PurePosixPath(p.strip("""/""" ) ) __lowerCAmelCase : int = p.parent if root == path: __lowerCAmelCase : int = f __lowerCAmelCase : Optional[int] = list(paths.values() ) if detail: return out else: return sorted(f["""name"""] for f in out )
651
1
import os from collections.abc import Iterator def a__ ( a = "." ) -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(a ): A_ : List[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(a )[1] in (".py", ".ipynb"): yield os.path.join(a , a ).lstrip('''./''' ) def a__ ( a ) -> int: return f"""{i * ' '}*""" if i else "\n##" def a__ ( a , a ) -> str: A_ : Optional[int] = old_path.split(os.sep ) for i, new_part in enumerate(new_path.split(os.sep ) ): if (i + 1 > len(a ) or old_parts[i] != new_part) and new_part: print(f"""{md_prefix(a )} {new_part.replace('_' , ' ' ).title()}""" ) return new_path def a__ ( a = "." ) -> None: A_ : List[str] = '''''' for filepath in sorted(good_file_paths(a ) ): A_ : List[Any] = os.path.split(a ) if filepath != old_path: A_ : Dict = print_path(a , a ) A_ : Any = (filepath.count(os.sep ) + 1) if filepath else 0 A_ : Dict = f"""{filepath}/{filename}""".replace(''' ''' , '''%20''' ) A_ : Optional[int] = os.path.splitext(filename.replace('''_''' , ''' ''' ).title() )[0] print(f"""{md_prefix(a )} [{filename}]({url})""" ) if __name__ == "__main__": print_directory_md('.')
713
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCAmelCase = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys _lowerCAmelCase = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
236
0
import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType lowercase_ , lowercase_ , lowercase_ = False, False, False @dataclass class __UpperCamelCase : """simple docstring""" lowerCAmelCase_ = None lowerCAmelCase_ = True lowerCAmelCase_ = True lowerCAmelCase_ = None # Automatically constructed lowerCAmelCase_ = "dict" lowerCAmelCase_ = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) lowerCAmelCase_ = field(default='''Audio''' , init=lowerCAmelCase__ , repr=lowerCAmelCase__ ) def __call__( self : int ): """simple docstring""" return self.pa_type def UpperCAmelCase__ ( self : str , _A : Union[str, bytes, dict] ): """simple docstring""" try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError('''To support encoding audio data, please install \'soundfile\'.''' ) from err if isinstance(_A , _A ): return {"bytes": None, "path": value} elif isinstance(_A , _A ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes __SCREAMING_SNAKE_CASE : List[Any] = BytesIO() sf.write(_A , value['''array'''] , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} elif value.get('''path''' ) is not None and os.path.isfile(value['''path'''] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith('''pcm''' ): # "PCM" only has raw audio bytes if value.get('''sampling_rate''' ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError('''To use PCM files, please specify a \'sampling_rate\' in Audio object''' ) if value.get('''bytes''' ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) __SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(value['''bytes'''] , dtype=np.intaa ).astype(np.floataa ) / 3_2767 else: __SCREAMING_SNAKE_CASE : Optional[int] = np.memmap(value['''path'''] , dtype='''h''' , mode='''r''' ).astype(np.floataa ) / 3_2767 __SCREAMING_SNAKE_CASE : str = BytesIO(bytes() ) sf.write(_A , _A , value['''sampling_rate'''] , format='''wav''' ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get('''path''' )} elif value.get('''bytes''' ) is not None or value.get('''path''' ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get('''bytes''' ), "path": value.get('''path''' )} else: raise ValueError( F'''An audio sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.''' ) def UpperCAmelCase__ ( self : List[Any] , _A : dict , _A : Optional[Dict[str, Union[str, bool, None]]] = None ): """simple docstring""" if not self.decode: raise RuntimeError('''Decoding is disabled for this feature. Please use Audio(decode=True) instead.''' ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Optional[Any] = (value['''path'''], BytesIO(value['''bytes'''] )) if value['''bytes'''] is not None else (value['''path'''], None) if path is None and file is None: raise ValueError(F'''An audio sample should have one of \'path\' or \'bytes\' but both are None in {value}.''' ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError('''To support decoding audio files, please install \'librosa\' and \'soundfile\'.''' ) from err __SCREAMING_SNAKE_CASE : List[Any] = xsplitext(_A )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( '''Decoding \'opus\' files requires system library \'libsndfile\'>=1.0.31, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( '''Decoding \'mp3\' files requires system library \'libsndfile\'>=1.1.0, ''' '''You can try to update `soundfile` python library: `pip install "soundfile>=0.12.1"`. ''' ) if file is None: __SCREAMING_SNAKE_CASE : str = token_per_repo_id or {} __SCREAMING_SNAKE_CASE : int = path.split('''::''' )[-1] try: __SCREAMING_SNAKE_CASE : int = string_to_dict(_A , config.HUB_DATASETS_URL )['''repo_id'''] __SCREAMING_SNAKE_CASE : Union[str, Any] = token_per_repo_id[repo_id] except (ValueError, KeyError): __SCREAMING_SNAKE_CASE : str = None with xopen(_A , '''rb''' , use_auth_token=_A ) as f: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = sf.read(_A ) else: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : int = sf.read(_A ) __SCREAMING_SNAKE_CASE : Tuple = array.T if self.mono: __SCREAMING_SNAKE_CASE : List[Any] = librosa.to_mono(_A ) if self.sampling_rate and self.sampling_rate != sampling_rate: __SCREAMING_SNAKE_CASE : Any = librosa.resample(_A , orig_sr=_A , target_sr=self.sampling_rate ) __SCREAMING_SNAKE_CASE : List[Any] = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def UpperCAmelCase__ ( self : Any ): """simple docstring""" from .features import Value if self.decode: raise ValueError('''Cannot flatten a decoded Audio feature.''' ) return { "bytes": Value('''binary''' ), "path": Value('''string''' ), } def UpperCAmelCase__ ( self : Any , _A : Union[pa.StringArray, pa.StructArray] ): """simple docstring""" if pa.types.is_string(storage.type ): __SCREAMING_SNAKE_CASE : str = pa.array([None] * len(_A ) , type=pa.binary() ) __SCREAMING_SNAKE_CASE : int = pa.StructArray.from_arrays([bytes_array, storage] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): __SCREAMING_SNAKE_CASE : Dict = pa.array([None] * len(_A ) , type=pa.string() ) __SCREAMING_SNAKE_CASE : List[Any] = pa.StructArray.from_arrays([storage, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices('''array''' ): __SCREAMING_SNAKE_CASE : Optional[Any] = pa.array([Audio().encode_example(_A ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index('''bytes''' ) >= 0: __SCREAMING_SNAKE_CASE : List[str] = storage.field('''bytes''' ) else: __SCREAMING_SNAKE_CASE : Optional[int] = pa.array([None] * len(_A ) , type=pa.binary() ) if storage.type.get_field_index('''path''' ) >= 0: __SCREAMING_SNAKE_CASE : Tuple = storage.field('''path''' ) else: __SCREAMING_SNAKE_CASE : int = pa.array([None] * len(_A ) , type=pa.string() ) __SCREAMING_SNAKE_CASE : List[str] = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=storage.is_null() ) return array_cast(_A , self.pa_type ) def UpperCAmelCase__ ( self : Union[str, Any] , _A : pa.StructArray ): """simple docstring""" @no_op_if_value_is_null def path_to_bytes(_A : Tuple ): with xopen(_A , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : List[Any] = f.read() return bytes_ __SCREAMING_SNAKE_CASE : Optional[Any] = pa.array( [ (path_to_bytes(x['''path'''] ) if x['''bytes'''] is None else x['''bytes''']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) __SCREAMING_SNAKE_CASE : Tuple = pa.array( [os.path.basename(_A ) if path is not None else None for path in storage.field('''path''' ).to_pylist()] , type=pa.string() , ) __SCREAMING_SNAKE_CASE : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] , ['''bytes''', '''path'''] , mask=bytes_array.is_null() ) return array_cast(_A , self.pa_type )
74
import argparse import os import re import packaging.version __a = """examples/""" __a = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } __a = { """init""": """src/diffusers/__init__.py""", """setup""": """setup.py""", } __a = """README.md""" def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ->Optional[Any]: with open(lowerCAmelCase_ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCAmelCase = f.read() UpperCAmelCase , UpperCAmelCase = REPLACE_PATTERNS[pattern] UpperCAmelCase = replace.replace("""VERSION""" , lowerCAmelCase_ ) UpperCAmelCase = re_pattern.sub(lowerCAmelCase_ , lowerCAmelCase_ ) with open(lowerCAmelCase_ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.write(lowerCAmelCase_ ) def _UpperCamelCase ( lowerCAmelCase_ ) ->int: for folder, directories, fnames in os.walk(lowerCAmelCase_ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("""research_projects""" ) if "legacy" in directories: directories.remove("""legacy""" ) for fname in fnames: if fname.endswith(""".py""" ): update_version_in_file(os.path.join(lowerCAmelCase_ , lowerCAmelCase_ ) , lowerCAmelCase_ , pattern="""examples""" ) def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=False ) ->Optional[int]: for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) if not patch: update_version_in_examples(lowerCAmelCase_ ) def _UpperCamelCase ( ) ->List[str]: UpperCAmelCase = """🤗 Transformers currently provides the following architectures""" UpperCAmelCase = """1. Want to contribute a new model?""" with open(lowerCAmelCase_ , """r""" , encoding="""utf-8""" , newline="""\n""" ) as f: UpperCAmelCase = f.readlines() # Find the start of the list. UpperCAmelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 UpperCAmelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("""1.""" ): UpperCAmelCase = lines[index].replace( """https://huggingface.co/docs/diffusers/main/model_doc""" , """https://huggingface.co/docs/diffusers/model_doc""" , ) index += 1 with open(lowerCAmelCase_ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f: f.writelines(lowerCAmelCase_ ) def _UpperCamelCase ( ) ->List[str]: with open(REPLACE_FILES["""init"""] , """r""" ) as f: UpperCAmelCase = f.read() UpperCAmelCase = REPLACE_PATTERNS["""init"""][0].search(lowerCAmelCase_ ).groups()[0] return packaging.version.parse(lowerCAmelCase_ ) def _UpperCamelCase ( lowerCAmelCase_=False ) ->int: UpperCAmelCase = get_version() if patch and default_version.is_devrelease: raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!""" ) if default_version.is_devrelease: UpperCAmelCase = default_version.base_version elif patch: UpperCAmelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: UpperCAmelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. UpperCAmelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(lowerCAmelCase_ ) == 0: UpperCAmelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase_ , patch=lowerCAmelCase_ ) def _UpperCamelCase ( ) ->int: UpperCAmelCase = get_version() UpperCAmelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" UpperCAmelCase = current_version.base_version # Check with the user we got that right. UpperCAmelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(lowerCAmelCase_ ) == 0: UpperCAmelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(lowerCAmelCase_ ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": __a = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") __a = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
377
0
from typing import TYPE_CHECKING from ....utils import _LazyModule UpperCamelCase_ = {"tokenization_tapex": ["TapexTokenizer"]} if TYPE_CHECKING: from .tokenization_tapex import TapexTokenizer else: import sys UpperCamelCase_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
376
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class a ( unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[int] ): """simple docstring""" __lowerCAmelCase = [[1, 2, 4], [1, 2, 3, 4]] __lowerCAmelCase = DisjunctiveConstraint(snake_case__ ) self.assertTrue(isinstance(dc.token_ids , snake_case__ ) ) with self.assertRaises(snake_case__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(snake_case__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : Tuple ): """simple docstring""" __lowerCAmelCase = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(snake_case__ ): DisjunctiveConstraint(snake_case__ ) # fails here def UpperCAmelCase__ ( self : Union[str, Any] ): """simple docstring""" __lowerCAmelCase = [[1, 2, 3], [1, 2, 4]] __lowerCAmelCase = DisjunctiveConstraint(snake_case__ ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 ) __lowerCAmelCase = stepped is True and completed is False and reset is False self.assertTrue(snake_case__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 ) __lowerCAmelCase = stepped is True and completed is False and reset is False self.assertTrue(snake_case__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(3 ) __lowerCAmelCase = stepped is True and completed is True and reset is False self.assertTrue(snake_case__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : Optional[Any] ): """simple docstring""" __lowerCAmelCase = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] __lowerCAmelCase = DisjunctiveConstraint(snake_case__ ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
376
1
from ....configuration_utils import PretrainedConfig from ....utils import logging lowercase : Dict = logging.get_logger(__name__) # TODO: upload to AWS lowercase : Tuple = { 'yjernite/retribert-base-uncased': ( 'https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json' ), } class lowerCamelCase__ ( __lowercase): '''simple docstring''' _A = 'retribert' def __init__( self :List[str] , a :Tuple=3_0_5_2_2 , a :List[str]=7_6_8 , a :Dict=8 , a :int=1_2 , a :Optional[Any]=3_0_7_2 , a :Dict="gelu" , a :Tuple=0.1 , a :Tuple=0.1 , a :Any=5_1_2 , a :Union[str, Any]=2 , a :int=0.02 , a :List[Any]=1E-1_2 , a :Dict=True , a :Union[str, Any]=1_2_8 , a :List[str]=0 , **a :Any , ) -> List[str]: super().__init__(pad_token_id=a , **a ) __UpperCamelCase : List[Any] = vocab_size __UpperCamelCase : Optional[int] = hidden_size __UpperCamelCase : int = num_hidden_layers __UpperCamelCase : Tuple = num_attention_heads __UpperCamelCase : str = hidden_act __UpperCamelCase : Any = intermediate_size __UpperCamelCase : str = hidden_dropout_prob __UpperCamelCase : Tuple = attention_probs_dropout_prob __UpperCamelCase : List[str] = max_position_embeddings __UpperCamelCase : List[Any] = type_vocab_size __UpperCamelCase : Tuple = initializer_range __UpperCamelCase : str = layer_norm_eps __UpperCamelCase : List[Any] = share_encoders __UpperCamelCase : Union[str, Any] = projection_dim
557
from __future__ import annotations class lowerCamelCase__ : '''simple docstring''' def __init__( self :Dict , a :str , a :str ) -> Union[str, Any]: __UpperCamelCase , __UpperCamelCase : Optional[int] = text, pattern __UpperCamelCase , __UpperCamelCase : Tuple = len(a ), len(a ) def _lowerCamelCase ( self :Any , a :str ) -> int: for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def _lowerCamelCase ( self :str , a :int ) -> int: for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def _lowerCamelCase ( self :Union[str, Any] ) -> list[int]: # searches pattern in text and returns index positions __UpperCamelCase : Any = [] for i in range(self.textLen - self.patLen + 1 ): __UpperCamelCase : List[Any] = self.mismatch_in_text(a ) if mismatch_index == -1: positions.append(a ) else: __UpperCamelCase : Any = self.match_in_pattern(self.text[mismatch_index] ) __UpperCamelCase : Dict = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions lowercase : Any = 'ABAABA' lowercase : str = 'AB' lowercase : str = BoyerMooreSearch(text, pattern) lowercase : Union[str, Any] = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
557
1
"""simple docstring""" import argparse import copy def _lowerCAmelCase ( __lowerCamelCase:int ): '''simple docstring''' __magic_name__ = {} with open(__lowerCamelCase ) as f: for line in f: if line.split()[0] not in dict_of_neighbours: __magic_name__ = [] _list.append([line.split()[1], line.split()[2]] ) __magic_name__ = _list else: dict_of_neighbours[line.split()[0]].append( [line.split()[1], line.split()[2]] ) if line.split()[1] not in dict_of_neighbours: __magic_name__ = [] _list.append([line.split()[0], line.split()[2]] ) __magic_name__ = _list else: dict_of_neighbours[line.split()[1]].append( [line.split()[0], line.split()[2]] ) return dict_of_neighbours def _lowerCAmelCase ( __lowerCamelCase:Any , __lowerCamelCase:Optional[int] ): '''simple docstring''' with open(__lowerCamelCase ) as f: __magic_name__ = f.read(1 ) __magic_name__ = start_node __magic_name__ = [] __magic_name__ = start_node __magic_name__ = 0 while visiting not in first_solution: __magic_name__ = 1_0_0_0_0 for k in dict_of_neighbours[visiting]: if int(k[1] ) < int(__lowerCamelCase ) and k[0] not in first_solution: __magic_name__ = k[1] __magic_name__ = k[0] first_solution.append(__lowerCamelCase ) __magic_name__ = distance_of_first_solution + int(__lowerCamelCase ) __magic_name__ = best_node first_solution.append(__lowerCamelCase ) __magic_name__ = 0 for k in dict_of_neighbours[first_solution[-2]]: if k[0] == start_node: break position += 1 __magic_name__ = ( distance_of_first_solution + int(dict_of_neighbours[first_solution[-2]][position][1] ) - 1_0_0_0_0 ) return first_solution, distance_of_first_solution def _lowerCAmelCase ( __lowerCamelCase:Any , __lowerCamelCase:Tuple ): '''simple docstring''' __magic_name__ = [] for n in solution[1:-1]: __magic_name__ = solution.index(__lowerCamelCase ) for kn in solution[1:-1]: __magic_name__ = solution.index(__lowerCamelCase ) if n == kn: continue __magic_name__ = copy.deepcopy(__lowerCamelCase ) __magic_name__ = kn __magic_name__ = n __magic_name__ = 0 for k in _tmp[:-1]: __magic_name__ = _tmp[_tmp.index(__lowerCamelCase ) + 1] for i in dict_of_neighbours[k]: if i[0] == next_node: __magic_name__ = distance + int(i[1] ) _tmp.append(__lowerCamelCase ) if _tmp not in neighborhood_of_solution: neighborhood_of_solution.append(_tmp ) __magic_name__ = len(neighborhood_of_solution[0] ) - 1 neighborhood_of_solution.sort(key=lambda __lowerCamelCase : x[index_of_last_item_in_the_list] ) return neighborhood_of_solution def _lowerCAmelCase ( __lowerCamelCase:Union[str, Any] , __lowerCamelCase:List[str] , __lowerCamelCase:List[Any] , __lowerCamelCase:Any , __lowerCamelCase:int ): '''simple docstring''' __magic_name__ = 1 __magic_name__ = first_solution __magic_name__ = [] __magic_name__ = distance_of_first_solution __magic_name__ = solution while count <= iters: __magic_name__ = find_neighborhood(__lowerCamelCase , __lowerCamelCase ) __magic_name__ = 0 __magic_name__ = neighborhood[index_of_best_solution] __magic_name__ = len(__lowerCamelCase ) - 1 __magic_name__ = False while not found: __magic_name__ = 0 while i < len(__lowerCamelCase ): if best_solution[i] != solution[i]: __magic_name__ = best_solution[i] __magic_name__ = solution[i] break __magic_name__ = i + 1 if [first_exchange_node, second_exchange_node] not in tabu_list and [ second_exchange_node, first_exchange_node, ] not in tabu_list: tabu_list.append([first_exchange_node, second_exchange_node] ) __magic_name__ = True __magic_name__ = best_solution[:-1] __magic_name__ = neighborhood[index_of_best_solution][best_cost_index] if cost < best_cost: __magic_name__ = cost __magic_name__ = solution else: __magic_name__ = index_of_best_solution + 1 __magic_name__ = neighborhood[index_of_best_solution] if len(__lowerCamelCase ) >= size: tabu_list.pop(0 ) __magic_name__ = count + 1 return best_solution_ever, best_cost def _lowerCAmelCase ( __lowerCamelCase:Optional[Any]=None ): '''simple docstring''' __magic_name__ = generate_neighbours(args.File ) __magic_name__ , __magic_name__ = generate_first_solution( args.File , __lowerCamelCase ) __magic_name__ , __magic_name__ = tabu_search( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , args.Iterations , args.Size , ) print(f'''Best solution: {best_sol}, with total distance: {best_cost}.''' ) if __name__ == "__main__": lowercase = argparse.ArgumentParser(description='''Tabu Search''') parser.add_argument( '''-f''', '''--File''', type=str, help='''Path to the file containing the data''', required=True, ) parser.add_argument( '''-i''', '''--Iterations''', type=int, help='''How many iterations the algorithm should perform''', required=True, ) parser.add_argument( '''-s''', '''--Size''', type=int, help='''Size of the tabu list''', required=True ) # Pass the arguments to main method main(parser.parse_args())
468
"""simple docstring""" 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 = get_tests_dir('''fixtures/test_sentencepiece.model''') if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowercase = 250004 lowercase = 250020 @require_sentencepiece @require_tokenizers class A_ ( snake_case_ , unittest.TestCase ): UpperCAmelCase__ = MBartaaTokenizer UpperCAmelCase__ = MBartaaTokenizerFast UpperCAmelCase__ = True UpperCAmelCase__ = True def _snake_case ( self : Any ) -> Dict: super().setUp() # We have a SentencePiece fixture for testing __magic_name__ = MBartaaTokenizer(__lowerCamelCase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self : Dict ) -> List[Any]: __magic_name__ = "<s>" __magic_name__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) , __lowerCamelCase ) def _snake_case ( self : int ) -> Union[str, Any]: __magic_name__ = 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(__lowerCamelCase ) , 1_0_5_4 ) def _snake_case ( self : Any ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_0_5_4 ) def _snake_case ( self : str ) -> Optional[Any]: __magic_name__ = MBartaaTokenizer(__lowerCamelCase , src_lang="en_XX" , tgt_lang="ro_RO" , keep_accents=__lowerCamelCase ) __magic_name__ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [value + tokenizer.fairseq_offset for value in [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2]] , ) __magic_name__ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __lowerCamelCase , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", "."] , ) __magic_name__ = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 2, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 2, 4] ] , ) __magic_name__ = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", "."] , ) @slow def _snake_case ( self : List[str] ) -> List[str]: # fmt: off __magic_name__ = {"input_ids": [[2_5_0_0_0_4, 1_1_0_6_2, 8_2_7_7_2, 7, 1_5, 8_2_7_7_2, 5_3_8, 5_1_5_2_9, 2_3_7, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 2_1_5_1_7_5, 1_3_1_4, 1_3_6, 1_7_1_9_8, 1_2_9_0, 2_0_6, 9, 5_6_3_5_9, 4_2, 1_2_2_0_0_9, 9, 1_6_4_6_6, 1_6, 8_7_3_4_4, 4_5_3_7, 9, 4_7_1_7, 7_8_3_8_1, 6, 1_5_9_9_5_8, 7, 1_5, 2_4_4_8_0, 6_1_8, 4, 5_2_7, 2_2_6_9_3, 5_4_2_8, 4, 2_7_7_7, 2_4_4_8_0, 9_8_7_4, 4, 4_3_5_2_3, 5_9_4, 4, 8_0_3, 1_8_3_9_2, 3_3_1_8_9, 1_8, 4, 4_3_5_2_3, 2_4_4_4_7, 1_2_3_9_9, 1_0_0, 2_4_9_5_5, 8_3_6_5_8, 9_6_2_6, 1_4_4_0_5_7, 1_5, 8_3_9, 2_2_3_3_5, 1_6, 1_3_6, 2_4_9_5_5, 8_3_6_5_8, 8_3_4_7_9, 1_5, 3_9_1_0_2, 7_2_4, 1_6, 6_7_8, 6_4_5, 2_7_8_9, 1_3_2_8, 4_5_8_9, 4_2, 1_2_2_0_0_9, 1_1_5_7_7_4, 2_3, 8_0_5, 1_3_2_8, 4_6_8_7_6, 7, 1_3_6, 5_3_8_9_4, 1_9_4_0, 4_2_2_2_7, 4_1_1_5_9, 1_7_7_2_1, 8_2_3, 4_2_5, 4, 2_7_5_1_2, 9_8_7_2_2, 2_0_6, 1_3_6, 5_5_3_1, 4_9_7_0, 9_1_9, 1_7_3_3_6, 5, 2], [2_5_0_0_0_4, 2_0_0_8_0, 6_1_8, 8_3, 8_2_7_7_5, 4_7, 4_7_9, 9, 1_5_1_7, 7_3, 5_3_8_9_4, 3_3_3, 8_0_5_8_1, 1_1_0_1_1_7, 1_8_8_1_1, 5_2_5_6, 1_2_9_5, 5_1, 1_5_2_5_2_6, 2_9_7, 7_9_8_6, 3_9_0, 1_2_4_4_1_6, 5_3_8, 3_5_4_3_1, 2_1_4, 9_8, 1_5_0_4_4, 2_5_7_3_7, 1_3_6, 7_1_0_8, 4_3_7_0_1, 2_3, 7_5_6, 1_3_5_3_5_5, 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], [2_5_0_0_0_4, 5_8_1, 6_3_7_7_3, 1_1_9_4_5_5, 6, 1_4_7_7_9_7, 8_8_2_0_3, 7, 6_4_5, 7_0, 2_1, 3_2_8_5, 1_0_2_6_9, 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=__lowerCamelCase , model_name="facebook/mbart-large-50" , revision="d3913889c59cd5c9e456b269c376325eabad57e2" , ) def _snake_case ( self : int ) -> Any: 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 __magic_name__ = (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})''' ): __magic_name__ = self.rust_tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) __magic_name__ = self.tokenizer_class.from_pretrained(__lowerCamelCase , **__lowerCamelCase ) __magic_name__ = tempfile.mkdtemp() __magic_name__ = tokenizer_r.save_pretrained(__lowerCamelCase ) __magic_name__ = tokenizer_p.save_pretrained(__lowerCamelCase ) # 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 ) ) __magic_name__ = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(__lowerCamelCase , __lowerCamelCase ) # Checks everything loads correctly in the same way __magic_name__ = tokenizer_r.from_pretrained(__lowerCamelCase ) __magic_name__ = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__lowerCamelCase ) # Save tokenizer rust, legacy_format=True __magic_name__ = tempfile.mkdtemp() __magic_name__ = tokenizer_r.save_pretrained(__lowerCamelCase , legacy_format=__lowerCamelCase ) __magic_name__ = tokenizer_p.save_pretrained(__lowerCamelCase ) # Checks it save with the same files self.assertSequenceEqual(__lowerCamelCase , __lowerCamelCase ) # Checks everything loads correctly in the same way __magic_name__ = tokenizer_r.from_pretrained(__lowerCamelCase ) __magic_name__ = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) shutil.rmtree(__lowerCamelCase ) # Save tokenizer rust, legacy_format=False __magic_name__ = tempfile.mkdtemp() __magic_name__ = tokenizer_r.save_pretrained(__lowerCamelCase , legacy_format=__lowerCamelCase ) __magic_name__ = tokenizer_p.save_pretrained(__lowerCamelCase ) # 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 __magic_name__ = tokenizer_r.from_pretrained(__lowerCamelCase ) __magic_name__ = tokenizer_p.from_pretrained(__lowerCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__lowerCamelCase , __lowerCamelCase ) ) shutil.rmtree(__lowerCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class A_ ( unittest.TestCase ): UpperCAmelCase__ = '''facebook/mbart-large-50-one-to-many-mmt''' UpperCAmelCase__ = [ ''' 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.''', ] UpperCAmelCase__ = [ '''Ş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.''', ] UpperCAmelCase__ = [EN_CODE, 8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2] @classmethod def _snake_case ( cls : Any ) -> Dict: __magic_name__ = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) __magic_name__ = 1 return cls def _snake_case ( self : Any ) -> Dict: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 2_5_0_0_0_1 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 2_5_0_0_0_4 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 2_5_0_0_2_0 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["mr_IN"] , 2_5_0_0_3_8 ) def _snake_case ( self : Any ) -> str: __magic_name__ = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __lowerCamelCase ) def _snake_case ( self : Any ) -> List[str]: self.assertIn(__lowerCamelCase , self.tokenizer.all_special_ids ) __magic_name__ = [RO_CODE, 8_8_4, 9_0_1_9, 9_6, 9, 9_1_6, 8_6_7_9_2, 3_6, 1_8_7_4_3, 1_5_5_9_6, 5, 2] __magic_name__ = self.tokenizer.decode(__lowerCamelCase , skip_special_tokens=__lowerCamelCase ) __magic_name__ = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__lowerCamelCase ) self.assertEqual(__lowerCamelCase , __lowerCamelCase ) self.assertNotIn(self.tokenizer.eos_token , __lowerCamelCase ) def _snake_case ( self : int ) -> List[str]: __magic_name__ = ["this is gunna be a long sentence " * 2_0] assert isinstance(src_text[0] , __lowerCamelCase ) __magic_name__ = 1_0 __magic_name__ = self.tokenizer(__lowerCamelCase , max_length=__lowerCamelCase , truncation=__lowerCamelCase ).input_ids[0] self.assertEqual(ids[0] , __lowerCamelCase ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(__lowerCamelCase ) , __lowerCamelCase ) def _snake_case ( self : str ) -> Tuple: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [2_5_0_0_5_3, 2_5_0_0_0_1] ) def _snake_case ( self : Any ) -> str: __magic_name__ = tempfile.mkdtemp() __magic_name__ = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__lowerCamelCase ) __magic_name__ = MBartaaTokenizer.from_pretrained(__lowerCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __lowerCamelCase ) @require_torch def _snake_case ( self : int ) -> Dict: __magic_name__ = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__lowerCamelCase , return_tensors="pt" ) __magic_name__ = 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 _snake_case ( self : Dict ) -> Tuple: __magic_name__ = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) __magic_name__ = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(__lowerCamelCase , __lowerCamelCase ) self.assertEqual((2, 1_4) , batch.input_ids.shape ) self.assertEqual((2, 1_4) , batch.attention_mask.shape ) __magic_name__ = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __lowerCamelCase ) 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 _snake_case ( self : Optional[int] ) -> Dict: __magic_name__ = self.tokenizer(self.src_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=3 , return_tensors="pt" ) __magic_name__ = self.tokenizer( text_target=self.tgt_text , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=1_0 , return_tensors="pt" ) __magic_name__ = targets["input_ids"] __magic_name__ = shift_tokens_right(__lowerCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 1_0 ) @require_torch def _snake_case ( self : Optional[int] ) -> Tuple: __magic_name__ = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(__lowerCamelCase ) , { # en_XX, A, test, EOS "input_ids": [[2_5_0_0_0_4, 6_2, 3_0_3_4, 2]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 2_5_0_0_0_1, } , )
468
1
'''simple docstring''' import os from distutils.util import strtobool def _A ( A__ , A__ ): """simple docstring""" for e in env_keys: __lowercase = int(os.environ.get(A__ , -1 ) ) if val >= 0: return val return default def _A ( A__ , A__=False ): """simple docstring""" __lowercase = os.environ.get(A__ , str(A__ ) ) return strtobool(A__ ) == 1 # As its name indicates `strtobool` actually returns an int... def _A ( A__ , A__="no" ): """simple docstring""" __lowercase = os.environ.get(A__ , str(A__ ) ) return value
41
'''simple docstring''' import io import math from typing import Dict, Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import convert_to_rgb, normalize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, get_image_size, infer_channel_dimension_format, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_vision_available, logging from ...utils.import_utils import requires_backends if is_vision_available(): import textwrap from PIL import Image, ImageDraw, ImageFont if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowerCAmelCase__ = False lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = '''ybelkada/fonts''' def _A ( ): """simple docstring""" if is_torch_available() and not is_torch_greater_or_equal_than_1_11: raise ImportError( F"You are using torch=={torch.__version__}, but torch>=1.11.0 is required to use " '''Pix2StructImageProcessor. Please upgrade torch.''' ) def _A ( A__ , A__ , A__ ): """simple docstring""" requires_backends(A__ , ['''torch'''] ) _check_torch_version() __lowercase = image_tensor.unsqueeze(0 ) __lowercase = torch.nn.functional.unfold(A__ , (patch_height, patch_width) , stride=(patch_height, patch_width) ) __lowercase = patches.reshape(image_tensor.size(0 ) , image_tensor.size(1 ) , A__ , A__ , -1 ) __lowercase = patches.permute(0 , 4 , 2 , 3 , 1 ).reshape( image_tensor.size(2 ) // patch_height , image_tensor.size(3 ) // patch_width , image_tensor.size(1 ) * patch_height * patch_width , ) return patches.unsqueeze(0 ) def _A ( A__ , A__ = 36 , A__ = "black" , A__ = "white" , A__ = 5 , A__ = 5 , A__ = 5 , A__ = 5 , A__ = None , A__ = None , ): """simple docstring""" requires_backends(A__ , '''vision''' ) # Add new lines so that each line is no more than 80 characters. __lowercase = textwrap.TextWrapper(width=80 ) __lowercase = wrapper.wrap(text=A__ ) __lowercase = '''\n'''.join(A__ ) if font_bytes is not None and font_path is None: __lowercase = io.BytesIO(A__ ) elif font_path is not None: __lowercase = font_path else: __lowercase = hf_hub_download(A__ , '''Arial.TTF''' ) __lowercase = ImageFont.truetype(A__ , encoding='''UTF-8''' , size=A__ ) # Use a temporary canvas to determine the width and height in pixels when # rendering the text. __lowercase = ImageDraw.Draw(Image.new('''RGB''' , (1, 1) , A__ ) ) __lowercase , __lowercase , __lowercase , __lowercase = temp_draw.textbbox((0, 0) , A__ , A__ ) # Create the actual image with a bit of padding around the text. __lowercase = text_width + left_padding + right_padding __lowercase = text_height + top_padding + bottom_padding __lowercase = Image.new('''RGB''' , (image_width, image_height) , A__ ) __lowercase = ImageDraw.Draw(A__ ) draw.text(xy=(left_padding, top_padding) , text=A__ , fill=A__ , font=A__ ) return image def _A ( A__ , A__ , **A__ ): """simple docstring""" requires_backends(A__ , '''vision''' ) # Convert to PIL image if necessary __lowercase = to_pil_image(A__ ) __lowercase = render_text(A__ , **A__ ) __lowercase = max(header_image.width , image.width ) __lowercase = int(image.height * (new_width / image.width) ) __lowercase = int(header_image.height * (new_width / header_image.width) ) __lowercase = Image.new('''RGB''' , (new_width, new_height + new_header_height) , '''white''' ) new_image.paste(header_image.resize((new_width, new_header_height) ) , (0, 0) ) new_image.paste(image.resize((new_width, new_height) ) , (0, new_header_height) ) # Convert back to the original framework if necessary __lowercase = to_numpy_array(A__ ) if infer_channel_dimension_format(A__ ) == ChannelDimension.LAST: __lowercase = to_channel_dimension_format(A__ , ChannelDimension.LAST ) return new_image class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = ['flattened_patches'] def __init__( self : Any ,lowercase__ : bool = True ,lowercase__ : bool = True ,lowercase__ : Dict[str, int] = None ,lowercase__ : int = 2_0_4_8 ,lowercase__ : bool = False ,**lowercase__ : List[str] ,): super().__init__(**lowercase__ ) __lowercase = patch_size if patch_size is not None else {'''height''': 1_6, '''width''': 1_6} __lowercase = do_normalize __lowercase = do_convert_rgb __lowercase = max_patches __lowercase = is_vqa def SCREAMING_SNAKE_CASE ( self : int ,lowercase__ : np.ndarray ,lowercase__ : int ,lowercase__ : dict ,**lowercase__ : Tuple ): requires_backends(self.extract_flattened_patches ,'''torch''' ) _check_torch_version() # convert to torch __lowercase = to_channel_dimension_format(lowercase__ ,ChannelDimension.FIRST ) __lowercase = torch.from_numpy(lowercase__ ) __lowercase , __lowercase = patch_size['''height'''], patch_size['''width'''] __lowercase , __lowercase = get_image_size(lowercase__ ) # maximize scale s.t. __lowercase = math.sqrt(max_patches * (patch_height / image_height) * (patch_width / image_width) ) __lowercase = max(min(math.floor(scale * image_height / patch_height ) ,lowercase__ ) ,1 ) __lowercase = max(min(math.floor(scale * image_width / patch_width ) ,lowercase__ ) ,1 ) __lowercase = max(num_feasible_rows * patch_height ,1 ) __lowercase = max(num_feasible_cols * patch_width ,1 ) __lowercase = torch.nn.functional.interpolate( image.unsqueeze(0 ) ,size=(resized_height, resized_width) ,mode='''bilinear''' ,align_corners=lowercase__ ,antialias=lowercase__ ,).squeeze(0 ) # [1, rows, columns, patch_height * patch_width * image_channels] __lowercase = torch_extract_patches(lowercase__ ,lowercase__ ,lowercase__ ) __lowercase = patches.shape __lowercase = patches_shape[1] __lowercase = patches_shape[2] __lowercase = patches_shape[3] # [rows * columns, patch_height * patch_width * image_channels] __lowercase = patches.reshape([rows * columns, depth] ) # [rows * columns, 1] __lowercase = torch.arange(lowercase__ ).reshape([rows, 1] ).repeat(1 ,lowercase__ ).reshape([rows * columns, 1] ) __lowercase = torch.arange(lowercase__ ).reshape([1, columns] ).repeat(lowercase__ ,1 ).reshape([rows * columns, 1] ) # Offset by 1 so the ids do not contain zeros, which represent padding. row_ids += 1 col_ids += 1 # Prepare additional patch features. # [rows * columns, 1] __lowercase = row_ids.to(torch.floataa ) __lowercase = col_ids.to(torch.floataa ) # [rows * columns, 2 + patch_height * patch_width * image_channels] __lowercase = torch.cat([row_ids, col_ids, patches] ,-1 ) # [max_patches, 2 + patch_height * patch_width * image_channels] __lowercase = torch.nn.functional.pad(lowercase__ ,[0, 0, 0, max_patches - (rows * columns)] ).float() __lowercase = to_numpy_array(lowercase__ ) return result def SCREAMING_SNAKE_CASE ( self : str ,lowercase__ : np.ndarray ,lowercase__ : Optional[Union[str, ChannelDimension]] = None ,**lowercase__ : List[Any] ): if image.dtype == np.uinta: __lowercase = image.astype(np.floataa ) # take mean across the whole `image` __lowercase = np.mean(lowercase__ ) __lowercase = np.std(lowercase__ ) __lowercase = max(lowercase__ ,1.0 / math.sqrt(np.prod(image.shape ) ) ) return normalize(lowercase__ ,mean=lowercase__ ,std=lowercase__ ,**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : ImageInput ,lowercase__ : Optional[str] = None ,lowercase__ : bool = None ,lowercase__ : Optional[bool] = None ,lowercase__ : Optional[int] = None ,lowercase__ : Optional[Dict[str, int]] = None ,lowercase__ : Optional[Union[str, TensorType]] = None ,lowercase__ : ChannelDimension = ChannelDimension.FIRST ,**lowercase__ : List[Any] ,): __lowercase = do_normalize if do_normalize is not None else self.do_normalize __lowercase = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __lowercase = patch_size if patch_size is not None else self.patch_size __lowercase = max_patches if max_patches is not None else self.max_patches __lowercase = self.is_vqa if kwargs.get('''data_format''' ,lowercase__ ) is not None: raise ValueError('''data_format is not an accepted input as the outputs are ''' ) __lowercase = make_list_of_images(lowercase__ ) if not valid_images(lowercase__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) # PIL RGBA images are converted to RGB if do_convert_rgb: __lowercase = [convert_to_rgb(lowercase__ ) for image in images] # All transformations expect numpy arrays. __lowercase = [to_numpy_array(lowercase__ ) for image in images] if is_vqa: if header_text is None: raise ValueError('''A header text must be provided for VQA models.''' ) __lowercase = kwargs.pop('''font_bytes''' ,lowercase__ ) __lowercase = kwargs.pop('''font_path''' ,lowercase__ ) if isinstance(lowercase__ ,lowercase__ ): __lowercase = [header_text] * len(lowercase__ ) __lowercase = [ render_header(lowercase__ ,header_text[i] ,font_bytes=lowercase__ ,font_path=lowercase__ ) for i, image in enumerate(lowercase__ ) ] if do_normalize: __lowercase = [self.normalize(image=lowercase__ ) for image in images] # convert to torch tensor and permute __lowercase = [ self.extract_flattened_patches(image=lowercase__ ,max_patches=lowercase__ ,patch_size=lowercase__ ) for image in images ] # create attention mask in numpy __lowercase = [(image.sum(axis=-1 ) != 0).astype(np.floataa ) for image in images] __lowercase = BatchFeature( data={'''flattened_patches''': images, '''attention_mask''': attention_masks} ,tensor_type=lowercase__ ) return encoded_outputs
41
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowercase = { """configuration_bigbird_pegasus""": [ """BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BigBirdPegasusConfig""", """BigBirdPegasusOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST""", """BigBirdPegasusForCausalLM""", """BigBirdPegasusForConditionalGeneration""", """BigBirdPegasusForQuestionAnswering""", """BigBirdPegasusForSequenceClassification""", """BigBirdPegasusModel""", """BigBirdPegasusPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
135
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available __lowercase = {"""tokenization_herbert""": ["""HerbertTokenizer"""]} try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ["""HerbertTokenizerFast"""] if TYPE_CHECKING: from .tokenization_herbert import HerbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_herbert_fast import HerbertTokenizerFast else: import sys __lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
135
1
lowerCAmelCase_ = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 1_0: "a", 1_1: "b", 1_2: "c", 1_3: "d", 1_4: "e", 1_5: "f", } def A_ ( lowercase_ ) -> str: assert type(lowercase_ ) in (int, float) and decimal == int(lowercase_ ) _snake_case : str = int(lowercase_ ) _snake_case : Any = '''''' _snake_case : List[Any] = False if decimal < 0: _snake_case : List[str] = True decimal *= -1 while decimal > 0: _snake_case , _snake_case : Tuple = divmod(lowercase_ , 16 ) _snake_case : Tuple = values[remainder] + hexadecimal _snake_case : List[str] = '''0x''' + hexadecimal if negative: _snake_case : int = '''-''' + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
326
import datasets from .nmt_bleu import compute_bleu # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py lowerCAmelCase_ = "\\n@INPROCEEDINGS{Papineni02bleu:a,\n author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},\n title = {BLEU: a Method for Automatic Evaluation of Machine Translation},\n booktitle = {},\n year = {2002},\n pages = {311--318}\n}\n@inproceedings{lin-och-2004-orange,\n title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",\n author = \"Lin, Chin-Yew and\n Och, Franz Josef\",\n booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",\n month = \"aug 23{--}aug 27\",\n year = \"2004\",\n address = \"Geneva, Switzerland\",\n publisher = \"COLING\",\n url = \"https://www.aclweb.org/anthology/C04-1072\",\n pages = \"501--507\",\n}\n" lowerCAmelCase_ = "\\nBLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.\nQuality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,\nthe better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and\nremains one of the most popular automated and inexpensive metrics.\n\nScores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.\nThose scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness\nare not taken into account[citation needed].\n\nBLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1\nrepresenting more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the\nreference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional\nreference translations will increase the BLEU score.\n" lowerCAmelCase_ = "\nComputes BLEU score of translated segments against one or more references.\nArgs:\n predictions: list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n max_order: Maximum n-gram order to use when computing BLEU score.\n smooth: Whether or not to apply Lin et al. 2004 smoothing.\nReturns:\n 'bleu': bleu score,\n 'precisions': geometric mean of n-gram precisions,\n 'brevity_penalty': brevity penalty,\n 'length_ratio': ratio of lengths,\n 'translation_length': translation_length,\n 'reference_length': reference_length\nExamples:\n\n >>> predictions = [\n ... [\"hello\", \"there\", \"general\", \"kenobi\"], # tokenized prediction of the first sample\n ... [\"foo\", \"bar\", \"foobar\"] # tokenized prediction of the second sample\n ... ]\n >>> references = [\n ... [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]], # tokenized references for the first sample (2 references)\n ... [[\"foo\", \"bar\", \"foobar\"]] # tokenized references for the second sample (1 reference)\n ... ]\n >>> bleu = datasets.load_metric(\"bleu\")\n >>> results = bleu.compute(predictions=predictions, references=references)\n >>> print(results[\"bleu\"])\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class A (datasets.Metric ): def __a ( self ) -> int: '''simple docstring''' return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py'''] , reference_urls=[ '''https://en.wikipedia.org/wiki/BLEU''', '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''', ] , ) def __a ( self , lowercase_ , lowercase_ , lowercase_=4 , lowercase_=False ) -> str: '''simple docstring''' _snake_case : Any = compute_bleu( reference_corpus=lowercase_ , translation_corpus=lowercase_ , max_order=lowercase_ , smooth=lowercase_ ) ((_snake_case) , (_snake_case) , (_snake_case) , (_snake_case) , (_snake_case) , (_snake_case)) : str = score return { "bleu": bleu, "precisions": precisions, "brevity_penalty": bp, "length_ratio": ratio, "translation_length": translation_length, "reference_length": reference_length, }
326
1
import warnings warnings.warn( 'memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: ' '`from accelerate import find_executable_batch_size` to avoid this warning.', FutureWarning, )
260
from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run __lowerCAmelCase : List[str] =True except (ImportError, AttributeError): __lowerCAmelCase : Optional[int] =object def _UpperCamelCase ( *lowercase__ , **lowercase__ ): pass __lowerCAmelCase : Optional[int] =False __lowerCAmelCase : List[Any] =logging.get_logger('transformers-cli/serving') def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(lowercase__ , args.host , args.port , args.workers ) class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : dict class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] SCREAMING_SNAKE_CASE__ : Optional[List[int]] class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str class _lowercase ( A__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any class _lowercase ( A__ ): '''simple docstring''' @staticmethod def __magic_name__( lowerCAmelCase__ :ArgumentParser ) -> List[str]: __SCREAMING_SNAKE_CASE : Union[str, Any] = parser.add_parser( '''serve''' , help='''CLI tool to run inference requests through REST and GraphQL endpoints.''' ) serve_parser.add_argument( '''--task''' , type=lowerCAmelCase__ , choices=get_supported_tasks() , help='''The task to run the pipeline on''' , ) serve_parser.add_argument('''--host''' , type=lowerCAmelCase__ , default='''localhost''' , help='''Interface the server will listen on.''' ) serve_parser.add_argument('''--port''' , type=lowerCAmelCase__ , default=8_888 , help='''Port the serving will listen to.''' ) serve_parser.add_argument('''--workers''' , type=lowerCAmelCase__ , default=1 , help='''Number of http workers''' ) serve_parser.add_argument('''--model''' , type=lowerCAmelCase__ , help='''Model\'s name or path to stored model.''' ) serve_parser.add_argument('''--config''' , type=lowerCAmelCase__ , help='''Model\'s config name or path to stored model.''' ) serve_parser.add_argument('''--tokenizer''' , type=lowerCAmelCase__ , help='''Tokenizer name to use.''' ) serve_parser.add_argument( '''--device''' , type=lowerCAmelCase__ , default=-1 , help='''Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)''' , ) serve_parser.set_defaults(func=lowerCAmelCase__ ) def __init__( self :Tuple , lowerCAmelCase__ :Pipeline , lowerCAmelCase__ :str , lowerCAmelCase__ :int , lowerCAmelCase__ :int ) -> List[str]: __SCREAMING_SNAKE_CASE : Optional[Any] = pipeline __SCREAMING_SNAKE_CASE : Optional[Any] = host __SCREAMING_SNAKE_CASE : List[str] = port __SCREAMING_SNAKE_CASE : List[Any] = workers if not _serve_dependencies_installed: raise RuntimeError( '''Using serve command requires FastAPI and uvicorn. ''' '''Please install transformers with [serving]: pip install "transformers[serving]".''' '''Or install FastAPI and uvicorn separately.''' ) else: logger.info(f'''Serving model over {host}:{port}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = FastAPI( routes=[ APIRoute( '''/''' , self.model_info , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=['''GET'''] , ), APIRoute( '''/tokenize''' , self.tokenize , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=['''POST'''] , ), APIRoute( '''/detokenize''' , self.detokenize , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=['''POST'''] , ), APIRoute( '''/forward''' , self.forward , response_model=lowerCAmelCase__ , response_class=lowerCAmelCase__ , methods=['''POST'''] , ), ] , timeout=600 , ) def __magic_name__( self :Dict ) -> str: run(self._app , host=self.host , port=self.port , workers=self.workers ) def __magic_name__( self :str ) -> List[Any]: return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def __magic_name__( self :List[Any] , lowerCAmelCase__ :str = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ :bool = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) ) -> Any: try: __SCREAMING_SNAKE_CASE : int = self._pipeline.tokenizer.tokenize(lowerCAmelCase__ ) if return_ids: __SCREAMING_SNAKE_CASE : int = self._pipeline.tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) return ServeTokenizeResult(tokens=lowerCAmelCase__ , tokens_ids=lowerCAmelCase__ ) else: return ServeTokenizeResult(tokens=lowerCAmelCase__ ) except Exception as e: raise HTTPException(status_code=500 , detail={'''model''': '''''', '''error''': str(lowerCAmelCase__ )} ) def __magic_name__( self :Optional[Any] , lowerCAmelCase__ :List[int] = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ :bool = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , lowerCAmelCase__ :bool = Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) , ) -> Dict: try: __SCREAMING_SNAKE_CASE : Any = self._pipeline.tokenizer.decode(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return ServeDeTokenizeResult(model='''''' , text=lowerCAmelCase__ ) except Exception as e: raise HTTPException(status_code=500 , detail={'''model''': '''''', '''error''': str(lowerCAmelCase__ )} ) async def __magic_name__( self :Any , lowerCAmelCase__ :Optional[Any]=Body(lowerCAmelCase__ , embed=lowerCAmelCase__ ) ) -> List[str]: # Check we don't have empty string if len(lowerCAmelCase__ ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model __SCREAMING_SNAKE_CASE : int = self._pipeline(lowerCAmelCase__ ) return ServeForwardResult(output=lowerCAmelCase__ ) except Exception as e: raise HTTPException(500 , {'''error''': str(lowerCAmelCase__ )} )
260
1
def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: def count_of_possible_combinations(__lowerCAmelCase ) -> int: if target < 0: return 0 if target == 0: return 1 return sum(count_of_possible_combinations(target - item ) for item in array ) return count_of_possible_combinations(__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: def count_of_possible_combinations_with_dp_array( __lowerCAmelCase , __lowerCAmelCase ) -> int: if target < 0: return 0 if target == 0: return 1 if dp_array[target] != -1: return dp_array[target] snake_case__ = sum( count_of_possible_combinations_with_dp_array(target - item , __lowerCAmelCase ) for item in array ) snake_case__ = answer return answer snake_case__ = [-1] * (target + 1) return count_of_possible_combinations_with_dp_array(__lowerCAmelCase , __lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> int: snake_case__ = [0] * (target + 1) snake_case__ = 1 for i in range(1 , target + 1 ): for j in range(__lowerCAmelCase ): if i - array[j] >= 0: dp_array[i] += dp_array[i - array[j]] return dp_array[target] if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ : Any = 3 lowerCamelCase__ : int = 5 lowerCamelCase__ : List[Any] = [1, 2, 5] print(combination_sum_iv(n, array, target))
33
from ... import PretrainedConfig UpperCAmelCase__ = { "sijunhe/nezha-cn-base": "https://huggingface.co/sijunhe/nezha-cn-base/resolve/main/config.json", } class lowercase_ ( lowercase ): '''simple docstring''' __snake_case = NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP __snake_case = '''nezha''' def __init__( self : Union[str, Any] , __UpperCAmelCase : List[str]=21_128 , __UpperCAmelCase : Any=768 , __UpperCAmelCase : int=12 , __UpperCAmelCase : Optional[int]=12 , __UpperCAmelCase : Tuple=3_072 , __UpperCAmelCase : Union[str, Any]="gelu" , __UpperCAmelCase : List[str]=0.1 , __UpperCAmelCase : Any=0.1 , __UpperCAmelCase : str=512 , __UpperCAmelCase : List[Any]=64 , __UpperCAmelCase : Tuple=2 , __UpperCAmelCase : List[Any]=0.02 , __UpperCAmelCase : List[str]=1e-1_2 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Dict=0 , __UpperCAmelCase : Any=2 , __UpperCAmelCase : Optional[Any]=3 , __UpperCAmelCase : int=True , **__UpperCAmelCase : Optional[Any] , ) ->Any: """simple docstring""" super().__init__(pad_token_id=__UpperCAmelCase , bos_token_id=__UpperCAmelCase , eos_token_id=__UpperCAmelCase , **__UpperCAmelCase ) a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = hidden_act a = intermediate_size a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = max_relative_position a = type_vocab_size a = initializer_range a = layer_norm_eps a = classifier_dropout a = use_cache
117
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _lowercase ( UpperCAmelCase__, UpperCAmelCase__, unittest.TestCase ): _UpperCAmelCase = StableDiffusionPanoramaPipeline _UpperCAmelCase = TEXT_TO_IMAGE_PARAMS _UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS _UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS _UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def A ( self : Tuple ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) a = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) a = DDIMScheduler() torch.manual_seed(0 ) a = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) a = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) a = CLIPTextModel(__lowerCAmelCase ) a = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) a = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def A ( self : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict=0 ) -> Optional[int]: """simple docstring""" a = torch.manual_seed(__lowerCAmelCase ) a = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def A ( self : Optional[int] ) -> str: """simple docstring""" a = "cpu" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionPanoramaPipeline(**__lowerCAmelCase ) a = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) a = self.get_dummy_inputs(__lowerCAmelCase ) a = sd_pipe(**__lowerCAmelCase ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A ( self : str ) -> Dict: """simple docstring""" super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def A ( self : Any ) -> Optional[Any]: """simple docstring""" super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def A ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" a = "cpu" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionPanoramaPipeline(**__lowerCAmelCase ) a = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) a = self.get_dummy_inputs(__lowerCAmelCase ) a = "french fries" a = sd_pipe(**__lowerCAmelCase , negative_prompt=__lowerCAmelCase ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A ( self : List[str] ) -> str: """simple docstring""" a = "cpu" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = StableDiffusionPanoramaPipeline(**__lowerCAmelCase ) a = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) a = self.get_dummy_inputs(__lowerCAmelCase ) a = sd_pipe(**__lowerCAmelCase , view_batch_size=2 ) a = output.images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A ( self : str ) -> Any: """simple docstring""" a = "cpu" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" ) a = StableDiffusionPanoramaPipeline(**__lowerCAmelCase ) a = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) a = self.get_dummy_inputs(__lowerCAmelCase ) a = sd_pipe(**__lowerCAmelCase ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A ( self : List[str] ) -> List[Any]: """simple docstring""" a = "cpu" # ensure determinism for the device-dependent torch.Generator a = self.get_dummy_components() a = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , skip_prk_steps=__lowerCAmelCase ) a = StableDiffusionPanoramaPipeline(**__lowerCAmelCase ) a = sd_pipe.to(__lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=__lowerCAmelCase ) a = self.get_dummy_inputs(__lowerCAmelCase ) a = sd_pipe(**__lowerCAmelCase ).images a = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _lowercase ( unittest.TestCase ): def A ( self : List[str] ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def A ( self : Optional[Any] , __lowerCAmelCase : List[str]=0 ) -> Tuple: """simple docstring""" a = torch.manual_seed(__lowerCAmelCase ) a = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def A ( self : Tuple ) -> Union[str, Any]: """simple docstring""" a = "stabilityai/stable-diffusion-2-base" a = DDIMScheduler.from_pretrained(__lowerCAmelCase , subfolder="scheduler" ) a = StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase , scheduler=__lowerCAmelCase , safety_checker=__lowerCAmelCase ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() a = self.get_inputs() a = pipe(**__lowerCAmelCase ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) a = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def A ( self : Optional[int] ) -> List[Any]: """simple docstring""" a = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=__lowerCAmelCase ) a = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() a = self.get_inputs() a = pipe(**__lowerCAmelCase ).images a = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) a = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def A ( self : Dict ) -> int: """simple docstring""" a = 0 def callback_fn(__lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : torch.FloatTensor ) -> None: a = True nonlocal number_of_steps number_of_steps += 1 if step == 1: a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) a = latents[0, -3:, -3:, -1] a = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: a = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) a = latents[0, -3:, -3:, -1] a = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 a = False a = "stabilityai/stable-diffusion-2-base" a = DDIMScheduler.from_pretrained(__lowerCAmelCase , subfolder="scheduler" ) a = StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase , scheduler=__lowerCAmelCase , safety_checker=__lowerCAmelCase ) a = pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing() a = self.get_inputs() pipe(**__lowerCAmelCase , callback=__lowerCAmelCase , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def A ( self : List[str] ) -> Optional[Any]: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a = "stabilityai/stable-diffusion-2-base" a = DDIMScheduler.from_pretrained(__lowerCAmelCase , subfolder="scheduler" ) a = StableDiffusionPanoramaPipeline.from_pretrained(__lowerCAmelCase , scheduler=__lowerCAmelCase , safety_checker=__lowerCAmelCase ) a = pipe.to(__lowerCAmelCase ) pipe.set_progress_bar_config(disable=__lowerCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() a = self.get_inputs() a = pipe(**__lowerCAmelCase ) a = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
32
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class _lowercase : def __init__( self : List[str] ) -> List[str]: """simple docstring""" a = "" a = "" a = [] a = 0 a = 256 a = 0 a = 0 a = 0 a = 0 def A ( self : Optional[Any] , __lowerCAmelCase : Any ) -> int: """simple docstring""" a = cva.imread(__lowerCAmelCase , 0 ) a = copy.deepcopy(self.img ) a , a , a = plt.hist(self.img.ravel() , 256 , [0, 256] , label="x" ) a = np.sum(__lowerCAmelCase ) for i in range(len(__lowerCAmelCase ) ): a = x[i] / self.k self.sk += prk a = (self.L - 1) * self.sk if self.rem != 0: a = int(last % last ) a = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__lowerCAmelCase ) a = int(np.ma.count(self.img ) / self.img[1].size ) a = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a = self.img[j][i] if num != self.last_list[num]: a = self.last_list[num] cva.imwrite("output_data/output.jpg" , self.img ) def A ( self : Any ) -> int: """simple docstring""" plt.hist(self.img.ravel() , 256 , [0, 256] ) def A ( self : Any ) -> int: """simple docstring""" cva.imshow("Output-Image" , self.img ) cva.imshow("Input-Image" , self.original_image ) cva.waitKey(5000 ) cva.destroyAllWindows() if __name__ == "__main__": A_ : List[Any] = os.path.join(os.path.basename(__file__), '''image_data/input.jpg''') A_ : int = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
32
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase: Union[str, Any] = logging.get_logger(__name__) class lowerCamelCase__ ( UpperCAmelCase ): UpperCamelCase__ ="encoder-decoder" UpperCamelCase__ =True def __init__( self : Optional[Any] , **lowercase__ : int ): super().__init__(**lowercase__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" _lowerCAmelCase = kwargs.pop('encoder' ) _lowerCAmelCase = encoder_config.pop('model_type' ) _lowerCAmelCase = kwargs.pop('decoder' ) _lowerCAmelCase = decoder_config.pop('model_type' ) from ..auto.configuration_auto import AutoConfig _lowerCAmelCase = AutoConfig.for_model(lowercase__ , **lowercase__ ) _lowerCAmelCase = AutoConfig.for_model(lowercase__ , **lowercase__ ) _lowerCAmelCase = True @classmethod def SCREAMING_SNAKE_CASE__ ( cls : Optional[int] , lowercase__ : PretrainedConfig , lowercase__ : PretrainedConfig , **lowercase__ : int ): logger.info('Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config' ) _lowerCAmelCase = True _lowerCAmelCase = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **lowercase__ ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): _lowerCAmelCase = copy.deepcopy(self.__dict__ ) _lowerCAmelCase = self.encoder.to_dict() _lowerCAmelCase = self.decoder.to_dict() _lowerCAmelCase = self.__class__.model_type return output
192
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase: Optional[Any] = logging.get_logger(__name__) _lowercase: Tuple = { '''andreasmadsen/efficient_mlm_m0.40''': ( '''https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json''' ), } class lowerCamelCase__ ( UpperCAmelCase ): UpperCamelCase__ ="roberta-prelayernorm" def __init__( self : int , lowercase__ : int=5_02_65 , lowercase__ : str=7_68 , lowercase__ : List[Any]=12 , lowercase__ : Any=12 , lowercase__ : Optional[Any]=30_72 , lowercase__ : List[Any]="gelu" , lowercase__ : str=0.1 , lowercase__ : List[Any]=0.1 , lowercase__ : Tuple=5_12 , lowercase__ : Optional[int]=2 , lowercase__ : Dict=0.0_2 , lowercase__ : Tuple=1e-12 , lowercase__ : Optional[int]=1 , lowercase__ : Optional[int]=0 , lowercase__ : Union[str, Any]=2 , lowercase__ : Any="absolute" , lowercase__ : Any=True , lowercase__ : Any=None , **lowercase__ : Optional[int] , ): super().__init__(pad_token_id=lowercase__ , bos_token_id=lowercase__ , eos_token_id=lowercase__ , **lowercase__ ) _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_act _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = position_embedding_type _lowerCAmelCase = use_cache _lowerCAmelCase = classifier_dropout class lowerCamelCase__ ( UpperCAmelCase ): @property def SCREAMING_SNAKE_CASE__ ( self : List[str] ): if self.task == "multiple-choice": _lowerCAmelCase = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _lowerCAmelCase = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
192
1
'''simple docstring''' import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class lowercase__ ( UpperCamelCase_): UpperCamelCase_ = ComputeEnvironment.AMAZON_SAGEMAKER UpperCamelCase_ = True UpperCamelCase_ = """ml.p3.2xlarge""" UpperCamelCase_ = """accelerate_sagemaker_execution_role""" UpperCamelCase_ = """hf-sm""" UpperCamelCase_ = """us-east-1""" UpperCamelCase_ = 1 UpperCamelCase_ = """accelerate-sagemaker-1""" UpperCamelCase_ = """1.6""" UpperCamelCase_ = """4.4""" UpperCamelCase_ = """train.py""" UpperCamelCase_ = [ """--model_name_or_path""", """bert""", """--do_train""", """False""", """--epochs""", """3""", """--learning_rate""", """5e-5""", """--max_steps""", """50.5""", ] UpperCamelCase_ = [ """--model_name_or_path""", """bert""", """--do_train""", """--do_test""", """False""", """--do_predict""", """--epochs""", """3""", """--learning_rate""", """5e-5""", """--max_steps""", """50.5""", ] class lowercase__ ( unittest.TestCase): def __A ( self : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args['''model_name_or_path'''] , UpperCamelCase__ ) assert isinstance(converted_args['''do_train'''] , UpperCamelCase__ ) assert isinstance(converted_args['''epochs'''] , UpperCamelCase__ ) assert isinstance(converted_args['''learning_rate'''] , UpperCamelCase__ ) assert isinstance(converted_args['''max_steps'''] , UpperCamelCase__ ) with pytest.raises(UpperCamelCase__ ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
717
from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def A ( _lowercase ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_text(_lowercase ) SCREAMING_SNAKE_CASE : Any = list(''' ''' + ascii_lowercase ) # what is our total sum of probabilities. SCREAMING_SNAKE_CASE : Tuple = sum(single_char_strings.values() ) # one length string SCREAMING_SNAKE_CASE : Tuple = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: SCREAMING_SNAKE_CASE : Tuple = single_char_strings[ch] SCREAMING_SNAKE_CASE : List[str] = my_str / all_sum my_fir_sum += prob * math.loga(_lowercase ) # entropy formula. # print entropy print(f"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string SCREAMING_SNAKE_CASE : Optional[Any] = sum(two_char_strings.values() ) SCREAMING_SNAKE_CASE : List[str] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: SCREAMING_SNAKE_CASE : Union[str, Any] = cha + cha if sequence in two_char_strings: SCREAMING_SNAKE_CASE : Any = two_char_strings[sequence] SCREAMING_SNAKE_CASE : Dict = int(_lowercase ) / all_sum my_sec_sum += prob * math.loga(_lowercase ) # print second entropy print(f"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def A ( _lowercase ): SCREAMING_SNAKE_CASE : Tuple = Counter() # type: ignore SCREAMING_SNAKE_CASE : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 , len(_lowercase ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def A ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
34
0
"""simple docstring""" import sys import turtle def a__ ( lowerCAmelCase__ , lowerCAmelCase__ ): return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def a__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ): my_pen.up() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) my_pen.goto(vertexa[0] , vertexa[1] ) if depth == 0: return triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) triangle(lowerCAmelCase__ , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , get_mid(lowerCAmelCase__ , lowerCAmelCase__ ) , depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( """Correct format for using this script: """ """python fractals.py <int:depth_for_fractal>""" ) lowerCamelCase = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("""red""") lowerCamelCase = [(-175, -125), (0, 175), (175, -125)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
82
"""simple docstring""" import unittest import numpy as np import requests 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 from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: lowerCamelCase = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowercase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[Any]=7 , _UpperCAmelCase : str=3 , _UpperCAmelCase : Any=18 , _UpperCAmelCase : int=30 , _UpperCAmelCase : Tuple=400 , _UpperCAmelCase : List[Any]=None , _UpperCAmelCase : str=True , _UpperCAmelCase : List[Any]=True , _UpperCAmelCase : int=None , ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = size if size is not None else {"height": 20, "width": 20} UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = image_size UpperCAmelCase_ = min_resolution UpperCAmelCase_ = max_resolution UpperCAmelCase_ = size UpperCAmelCase_ = do_normalize UpperCAmelCase_ = do_convert_rgb UpperCAmelCase_ = [512, 1024, 2048, 4096] UpperCAmelCase_ = patch_size if patch_size is not None else {"height": 16, "width": 16} def lowercase__ ( self : List[Any] ) -> List[Any]: '''simple docstring''' return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def lowercase__ ( self : List[Any] ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg" UpperCAmelCase_ = Image.open(requests.get(_UpperCAmelCase , stream=_UpperCAmelCase ).raw ).convert("RGB" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class lowercase__ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' UpperCamelCase = PixaStructImageProcessor if is_vision_available() else None def lowercase__ ( self : Optional[int] ) -> int: '''simple docstring''' UpperCAmelCase_ = PixaStructImageProcessingTester(self ) @property def lowercase__ ( self : List[Any] ) -> Any: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowercase__ ( self : Dict ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_UpperCAmelCase , "do_normalize" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "do_convert_rgb" ) ) def lowercase__ ( self : str ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = self.image_processor_tester.prepare_dummy_image() UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) UpperCAmelCase_ = 2048 UpperCAmelCase_ = image_processor(_UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def lowercase__ ( self : List[Any] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , Image.Image ) # Test not batched input UpperCAmelCase_ = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase_ = image_processor( _UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowercase__ ( self : str ) -> int: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , Image.Image ) # Test not batched input UpperCAmelCase_ = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 UpperCAmelCase_ = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(_UpperCAmelCase ): UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches UpperCAmelCase_ = "Hello" UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase , header_text=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase_ = image_processor( _UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase , header_text=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowercase__ ( self : str ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , numpify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , np.ndarray ) UpperCAmelCase_ = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase_ = image_processor( _UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def lowercase__ ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase , torchify=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , torch.Tensor ) # Test not batched input UpperCAmelCase_ = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase_ = image_processor( _UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='''`Pix2StructImageProcessor` requires `torch>=1.11.0`.''' , ) @require_torch @require_vision class lowercase__ ( SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' UpperCamelCase = PixaStructImageProcessor if is_vision_available() else None def lowercase__ ( self : List[str] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = PixaStructImageProcessingTester(self , num_channels=4 ) UpperCAmelCase_ = 3 @property def lowercase__ ( self : str ) -> Optional[int]: '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def lowercase__ ( self : str ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_UpperCAmelCase , "do_normalize" ) ) self.assertTrue(hasattr(_UpperCAmelCase , "do_convert_rgb" ) ) def lowercase__ ( self : List[str] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=_UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(_UpperCAmelCase , Image.Image ) # Test not batched input UpperCAmelCase_ = ( (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"]) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase_ = image_processor( image_inputs[0] , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase_ = image_processor( _UpperCAmelCase , return_tensors="pt" , max_patches=_UpperCAmelCase ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
82
1
'''simple docstring''' import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class UpperCAmelCase ( UpperCAmelCase_ ): _A : Any = """Speech2TextFeatureExtractor""" _A : List[Any] = """Speech2TextTokenizer""" def __init__( self , __A , __A ): super().__init__(__A , __A ) __UpperCAmelCase = self.feature_extractor __UpperCAmelCase = False def __call__( self , *__A , **__A ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*__A , **__A ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) __UpperCAmelCase = kwargs.pop('raw_speech' ) else: __UpperCAmelCase = kwargs.pop('audio' , __A ) __UpperCAmelCase = kwargs.pop('sampling_rate' , __A ) __UpperCAmelCase = kwargs.pop('text' , __A ) if len(__A ) > 0: __UpperCAmelCase = args[0] __UpperCAmelCase = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: __UpperCAmelCase = self.feature_extractor(__A , *__A , sampling_rate=__A , **__A ) if text is not None: __UpperCAmelCase = self.tokenizer(__A , **__A ) if text is None: return inputs elif audio is None: return encodings else: __UpperCAmelCase = encodings['input_ids'] return inputs def __lowerCamelCase ( self , *__A , **__A ): return self.tokenizer.batch_decode(*__A , **__A ) def __lowerCamelCase ( self , *__A , **__A ): return self.tokenizer.decode(*__A , **__A ) @contextmanager def __lowerCamelCase ( self ): warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) __UpperCAmelCase = True __UpperCAmelCase = self.tokenizer yield __UpperCAmelCase = self.feature_extractor __UpperCAmelCase = False
715
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex _A: int = logging.getLogger(__name__) class UpperCAmelCase : def __init__( self ): __UpperCAmelCase = False def __lowerCamelCase ( self , __A , __A , __A , __A ): if not self.initialized: __UpperCAmelCase = RagRetriever( __A , question_encoder_tokenizer=__A , generator_tokenizer=__A , index=__A , init_retrieval=__A , ) __UpperCAmelCase = True def __lowerCamelCase ( self ): self.retriever.index.init_index() def __lowerCamelCase ( self , __A , __A ): __UpperCAmelCase , __UpperCAmelCase = self.retriever._main_retrieve(__A , __A ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase ( UpperCAmelCase_ ): def __init__( self , __A , __A , __A , __A , __A=None ): if index is not None and index.is_initialized() and len(__A ) > 0: raise ValueError( 'When using Ray for distributed fine-tuning, ' 'you\'ll need to provide the paths instead, ' 'as the dataset and the index are loaded ' 'separately. More info in examples/rag/use_own_knowledge_dataset.py ' ) super().__init__( __A , question_encoder_tokenizer=__A , generator_tokenizer=__A , index=__A , init_retrieval=__A , ) __UpperCAmelCase = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(__A , __A , __A , __A ) for worker in self.retrieval_workers ] ) def __lowerCamelCase ( self ): logger.info('initializing retrieval' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCamelCase ( self , __A , __A ): if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. __UpperCAmelCase = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] __UpperCAmelCase , __UpperCAmelCase = ray.get(random_worker.retrieve.remote(__A , __A ) ) else: __UpperCAmelCase , __UpperCAmelCase = self._main_retrieve(__A , __A ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(__A ) @classmethod def __lowerCamelCase ( cls , __A , __A=None , **__A ): return super(__A , cls ).get_tokenizers(__A , __A , **__A ) @classmethod def __lowerCamelCase ( cls , __A , __A , __A=None , **__A ): __UpperCAmelCase = kwargs.pop('config' , __A ) or RagConfig.from_pretrained(__A , **__A ) __UpperCAmelCase = RagTokenizer.from_pretrained(__A , config=__A ) __UpperCAmelCase = rag_tokenizer.question_encoder __UpperCAmelCase = rag_tokenizer.generator if indexed_dataset is not None: __UpperCAmelCase = 'custom' __UpperCAmelCase = CustomHFIndex(config.retrieval_vector_size , __A ) else: __UpperCAmelCase = cls._build_index(__A ) return cls( __A , question_encoder_tokenizer=__A , generator_tokenizer=__A , retrieval_workers=__A , index=__A , )
617
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCamelCase : List[str] = { """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCamelCase : Union[str, Any] = [ """LILT_PRETRAINED_MODEL_ARCHIVE_LIST""", """LiltForQuestionAnswering""", """LiltForSequenceClassification""", """LiltForTokenClassification""", """LiltModel""", """LiltPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __UpperCamelCase : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
448
'''simple docstring''' import os def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: str = "matrix.txt" ) -> int: """simple docstring""" with open(os.path.join(os.path.dirname(SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__ ) ) as in_file: __a = in_file.read() __a = [[int(SCREAMING_SNAKE_CASE__ ) for cell in row.split(',' )] for row in data.strip().splitlines()] __a = [[0 for cell in row] for row in grid] __a = len(grid[0] ) __a = [[0 for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] __a = grid[0][0] for i in range(1, SCREAMING_SNAKE_CASE__ ): __a = grid[0][i] + dp[0][i - 1] for i in range(1, SCREAMING_SNAKE_CASE__ ): __a = grid[i][0] + dp[i - 1][0] for i in range(1, SCREAMING_SNAKE_CASE__ ): for j in range(1, SCREAMING_SNAKE_CASE__ ): __a = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"""{solution() = }""")
448
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase__ = { '''configuration_timesformer''': ['''TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TimesformerConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ '''TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TimesformerModel''', '''TimesformerForVideoClassification''', '''TimesformerPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
708
import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class snake_case__(unittest.TestCase ): """simple docstring""" def snake_case ( self : int ): lowercase__ : str = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) lowercase__ : Dict = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(SCREAMING_SNAKE_CASE ) lowercase__ : str = -1 lowercase__ : int = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE ) lowercase__ : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE ) lowercase__ : Dict = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: lowercase__ : str = TextStreamer(SCREAMING_SNAKE_CASE ) model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE , streamer=SCREAMING_SNAKE_CASE ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer lowercase__ : int = cs.out[:-1] self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def snake_case ( self : Optional[int] ): lowercase__ : str = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) lowercase__ : str = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(SCREAMING_SNAKE_CASE ) lowercase__ : Optional[Any] = -1 lowercase__ : Union[str, Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE ) lowercase__ : Optional[int] = model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE ) lowercase__ : int = tokenizer.decode(greedy_ids[0] ) lowercase__ : Union[str, Any] = TextIteratorStreamer(SCREAMING_SNAKE_CASE ) lowercase__ : Dict = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} lowercase__ : Optional[int] = Thread(target=model.generate , kwargs=SCREAMING_SNAKE_CASE ) thread.start() lowercase__ : List[Any] = "" for new_text in streamer: streamer_text += new_text self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def snake_case ( self : Union[str, Any] ): lowercase__ : Union[str, Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) lowercase__ : Union[str, Any] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(SCREAMING_SNAKE_CASE ) lowercase__ : Union[str, Any] = -1 lowercase__ : int = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE ) lowercase__ : Union[str, Any] = model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE ) lowercase__ : Any = greedy_ids[:, input_ids.shape[1] :] lowercase__ : Any = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: lowercase__ : str = TextStreamer(SCREAMING_SNAKE_CASE , skip_prompt=SCREAMING_SNAKE_CASE ) model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=10 , do_sample=SCREAMING_SNAKE_CASE , streamer=SCREAMING_SNAKE_CASE ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer lowercase__ : Optional[Any] = cs.out[:-1] self.assertEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) def snake_case ( self : Any ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them lowercase__ : List[str] = AutoTokenizer.from_pretrained("distilgpt2" ) lowercase__ : Tuple = AutoModelForCausalLM.from_pretrained("distilgpt2" ).to(SCREAMING_SNAKE_CASE ) lowercase__ : List[Any] = -1 lowercase__ : List[Any] = torch.ones((1, 5) , device=SCREAMING_SNAKE_CASE ).long() * model.config.bos_token_id with CaptureStdout() as cs: lowercase__ : Dict = TextStreamer(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE ) model.generate(SCREAMING_SNAKE_CASE , max_new_tokens=1 , do_sample=SCREAMING_SNAKE_CASE , streamer=SCREAMING_SNAKE_CASE ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token lowercase__ : List[Any] = cs.out[:-1] # Remove the final "\n" lowercase__ : Optional[int] = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="pt" ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def snake_case ( self : Optional[int] ): lowercase__ : Dict = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) lowercase__ : List[str] = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ).to(SCREAMING_SNAKE_CASE ) lowercase__ : int = -1 lowercase__ : Tuple = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(SCREAMING_SNAKE_CASE ) lowercase__ : List[Any] = TextIteratorStreamer(SCREAMING_SNAKE_CASE , timeout=0.001 ) lowercase__ : Union[str, Any] = {"input_ids": input_ids, "max_new_tokens": 10, "do_sample": False, "streamer": streamer} lowercase__ : Any = Thread(target=model.generate , kwargs=SCREAMING_SNAKE_CASE ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(SCREAMING_SNAKE_CASE ): lowercase__ : List[str] = "" for new_text in streamer: streamer_text += new_text
81
0
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def _snake_case ( __snake_case : dict ): """simple docstring""" return (data["data"], data["target"]) def _snake_case ( __snake_case : np.ndarray , __snake_case : np.ndarray , __snake_case : np.ndarray ): """simple docstring""" _lowerCamelCase : int = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(__snake_case , __snake_case ) # Predict target for test data _lowerCamelCase : str = xgb.predict(__snake_case ) _lowerCamelCase : Optional[Any] = predictions.reshape(len(__snake_case ) , 1 ) return predictions def _snake_case ( ): """simple docstring""" _lowerCamelCase : List[Any] = fetch_california_housing() _lowerCamelCase , _lowerCamelCase : Union[str, Any] = data_handling(__snake_case ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[Any] = train_test_split( __snake_case , __snake_case , test_size=0.25 , random_state=1 ) _lowerCamelCase : List[str] = xgboost(__snake_case , __snake_case , __snake_case ) # Error printing print(F'Mean Absolute Error : {mean_absolute_error(__snake_case , __snake_case )}' ) print(F'Mean Square Error : {mean_squared_error(__snake_case , __snake_case )}' ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
88
'''simple docstring''' def __snake_case ( UpperCAmelCase_ : str ): lowerCamelCase_ = "" for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def __snake_case ( UpperCAmelCase_ : str ): lowerCamelCase_ = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key lowerCamelCase_ = remove_duplicates(key.upper() ) lowerCamelCase_ = len(UpperCAmelCase_ ) # First fill cipher with key characters lowerCamelCase_ = {alphabet[i]: char for i, char in enumerate(UpperCAmelCase_ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(UpperCAmelCase_ ) , 26 ): lowerCamelCase_ = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 lowerCamelCase_ = alphabet[i - offset] lowerCamelCase_ = char return cipher_alphabet def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : dict[str, str] ): return "".join(cipher_map.get(UpperCAmelCase_ , UpperCAmelCase_ ) for ch in message.upper() ) def __snake_case ( UpperCAmelCase_ : str , UpperCAmelCase_ : dict[str, str] ): lowerCamelCase_ = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(UpperCAmelCase_ , UpperCAmelCase_ ) for ch in message.upper() ) def __snake_case ( ): lowerCamelCase_ = input("Enter message to encode or decode: " ).strip() lowerCamelCase_ = input("Enter keyword: " ).strip() lowerCamelCase_ = input("Encipher or decipher? E/D:" ).strip()[0].lower() try: lowerCamelCase_ = {"e": encipher, "d": decipher}[option] except KeyError: raise KeyError("invalid input option" ) lowerCamelCase_ = create_cipher_map(UpperCAmelCase_ ) print(func(UpperCAmelCase_ , UpperCAmelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
675
0
"""simple docstring""" import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class _SCREAMING_SNAKE_CASE ( unittest.TestCase ): def lowercase_ (self ): '''simple docstring''' _UpperCamelCase : Optional[Any] = logging.get_logger() # the current default level is logging.WARNING _UpperCamelCase : Any = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(lowerCAmelCase__ ) def lowercase_ (self ): '''simple docstring''' _UpperCamelCase : Union[str, Any] = logging.get_verbosity() _UpperCamelCase : Optional[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) _UpperCamelCase : str = """Testing 1, 2, 3""" # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(lowerCAmelCase__ ) as cl: logger.warning(lowerCAmelCase__ ) self.assertEqual(cl.out , msg + "\n" ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(lowerCAmelCase__ ) as cl: logger.warning(lowerCAmelCase__ ) self.assertEqual(cl.out , "" ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(lowerCAmelCase__ ) as cl: logger.warning(lowerCAmelCase__ ) self.assertEqual(cl.out , msg + "\n" ) # restore to the original level logging.set_verbosity(lowerCAmelCase__ ) @mockenv(TRANSFORMERS_VERBOSITY="error" ) def lowercase_ (self ): '''simple docstring''' transformers.utils.logging._reset_library_root_logger() # this action activates the env var _UpperCamelCase : int = logging.get_logger("transformers.models.bart.tokenization_bart" ) _UpperCamelCase : Optional[int] = os.getenv("TRANSFORMERS_VERBOSITY" , lowerCAmelCase__ ) _UpperCamelCase : Any = logging.log_levels[env_level_str] _UpperCamelCase : Dict = logging.get_verbosity() self.assertEqual( lowerCAmelCase__ , lowerCAmelCase__ , F"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}" , ) # restore to the original level _UpperCamelCase : int = """""" transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY="super-error" ) def lowercase_ (self ): '''simple docstring''' transformers.utils.logging._reset_library_root_logger() _UpperCamelCase : str = logging.logging.getLogger() with CaptureLogger(lowerCAmelCase__ ) as cl: # this action activates the env var logging.get_logger("transformers.models.bart.tokenization_bart" ) self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error" , cl.out ) # no need to restore as nothing was changed def lowercase_ (self ): '''simple docstring''' transformers.utils.logging._reset_library_root_logger() _UpperCamelCase : Optional[Any] = logging.get_logger("transformers.models.bart.tokenization_bart" ) _UpperCamelCase : List[Any] = """Testing 1, 2, 3""" with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1" ): # nothing should be logged as env var disables this method with CaptureLogger(lowerCAmelCase__ ) as cl: logger.warning_advice(lowerCAmelCase__ ) self.assertEqual(cl.out , "" ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="" ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(lowerCAmelCase__ ) as cl: logger.warning_advice(lowerCAmelCase__ ) self.assertEqual(cl.out , msg + "\n" ) def __lowerCAmelCase ( ) -> Any: disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
708
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) _SCREAMING_SNAKE_CASE = { """configuration_falcon""": ["""FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FalconConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _SCREAMING_SNAKE_CASE = [ """FALCON_PRETRAINED_MODEL_ARCHIVE_LIST""", """FalconForCausalLM""", """FalconModel""", """FalconPreTrainedModel""", """FalconForSequenceClassification""", """FalconForTokenClassification""", """FalconForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_falcon import FALCON_PRETRAINED_CONFIG_ARCHIVE_MAP, FalconConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_falcon import ( FALCON_PRETRAINED_MODEL_ARCHIVE_LIST, FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, FalconPreTrainedModel, ) else: import sys _SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
239
0
'''simple docstring''' import unittest import numpy as np from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A ( __lowercase , unittest.TestCase ): # FIXME: add fast tests pass @nightly @require_onnxruntime @require_torch_gpu class _A ( unittest.TestCase ): @property def lowercase__ ( self : str ) -> Optional[Any]: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def lowercase__ ( self : int ) -> Optional[Any]: """simple docstring""" __snake_case : str = ort.SessionOptions() __snake_case : Optional[Any] = False return options def lowercase__ ( self : Any ) -> Tuple: """simple docstring""" __snake_case : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) __snake_case : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) __snake_case : List[str] = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) __snake_case : str = """A red cat sitting on a park bench""" __snake_case : List[str] = np.random.RandomState(0 ) __snake_case : Optional[int] = pipe( prompt=__magic_name__ , image=__magic_name__ , mask_image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=10 , generator=__magic_name__ , output_type="""np""" , ) __snake_case : Tuple = output.images __snake_case : Dict = images[0, 2_55:2_58, 2_55:2_58, -1] assert images.shape == (1, 5_12, 5_12, 3) __snake_case : str = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def lowercase__ ( self : Union[str, Any] ) -> str: """simple docstring""" __snake_case : int = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo.png""" ) __snake_case : Tuple = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/in_paint/overture-creations-5sI6fQgYIuo_mask.png""" ) __snake_case : List[str] = LMSDiscreteScheduler.from_pretrained( """runwayml/stable-diffusion-inpainting""" , subfolder="""scheduler""" , revision="""onnx""" ) __snake_case : List[Any] = OnnxStableDiffusionInpaintPipeline.from_pretrained( """runwayml/stable-diffusion-inpainting""" , revision="""onnx""" , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) __snake_case : Union[str, Any] = """A red cat sitting on a park bench""" __snake_case : Union[str, Any] = np.random.RandomState(0 ) __snake_case : Optional[Any] = pipe( prompt=__magic_name__ , image=__magic_name__ , mask_image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=20 , generator=__magic_name__ , output_type="""np""" , ) __snake_case : Optional[int] = output.images __snake_case : Dict = images[0, 2_55:2_58, 2_55:2_58, -1] assert images.shape == (1, 5_12, 5_12, 3) __snake_case : Dict = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
26
def _UpperCAmelCase ( UpperCamelCase: int ): """simple docstring""" if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(UpperCamelCase , UpperCamelCase ): raise TypeError("Input value must be a 'int' type" ) return bin(UpperCamelCase ).count("1" ) if __name__ == "__main__": import doctest doctest.testmod()
611
0
"""simple docstring""" import os import sys import unittest __SCREAMING_SNAKE_CASE : List[str] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __SCREAMING_SNAKE_CASE : str = os.path.join(git_repo_path, 'src', 'transformers') __SCREAMING_SNAKE_CASE : Tuple = """ {0} = None """ __SCREAMING_SNAKE_CASE : List[str] = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) """ __SCREAMING_SNAKE_CASE : Optional[Any] = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ class __A (unittest.TestCase): '''simple docstring''' def lowerCAmelCase ( self : int ) ->Any: """simple docstring""" snake_case_ = find_backend(""" _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")""" ) self.assertIsNone(UpperCamelCase__ ) snake_case_ = find_backend(""" if not is_tokenizers_available():""" ) self.assertEqual(UpperCamelCase__ , """tokenizers""" ) snake_case_ = find_backend(""" if not is_tensorflow_text_available():""" ) self.assertEqual(UpperCamelCase__ , """tensorflow_text""" ) snake_case_ = find_backend(""" if not (is_sentencepiece_available() and is_tokenizers_available()):""" ) self.assertEqual(UpperCamelCase__ , """sentencepiece_and_tokenizers""" ) snake_case_ = find_backend( """ if not (is_sentencepiece_available() and is_tensorflow_text_available()):""" ) self.assertEqual(UpperCamelCase__ , """sentencepiece_and_tensorflow_text""" ) snake_case_ = find_backend( """ if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):""" ) self.assertEqual(UpperCamelCase__ , """sentencepiece_and_tokenizers_and_vision""" ) def lowerCAmelCase ( self : Tuple ) ->List[Any]: """simple docstring""" snake_case_ = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("""torch""" , UpperCamelCase__ ) self.assertIn("""tensorflow_text""" , UpperCamelCase__ ) self.assertIn("""sentencepiece_and_tokenizers""" , UpperCamelCase__ ) # Likewise, we can't assert on the exact content of a key self.assertIn("""BertModel""" , objects["""torch"""] ) self.assertIn("""TFBertModel""" , objects["""tf"""] ) self.assertIn("""FlaxBertModel""" , objects["""flax"""] ) self.assertIn("""BertModel""" , objects["""torch"""] ) self.assertIn("""TFBertTokenizer""" , objects["""tensorflow_text"""] ) self.assertIn("""convert_slow_tokenizer""" , objects["""sentencepiece_and_tokenizers"""] ) def lowerCAmelCase ( self : Tuple ) ->List[str]: """simple docstring""" snake_case_ = create_dummy_object("""CONSTANT""" , """\'torch\'""" ) self.assertEqual(UpperCamelCase__ , """\nCONSTANT = None\n""" ) snake_case_ = create_dummy_object("""function""" , """\'torch\'""" ) self.assertEqual( UpperCamelCase__ , """\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n""" ) snake_case_ = """ class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') """ snake_case_ = create_dummy_object("""FakeClass""" , """\'torch\'""" ) self.assertEqual(UpperCamelCase__ , UpperCamelCase__ ) def lowerCAmelCase ( self : List[Any] ) ->List[str]: """simple docstring""" snake_case_ = """# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, [\"torch\"]) class FakeClass(metaclass=DummyObject): _backends = [\"torch\"] def __init__(self, *args, **kwargs): requires_backends(self, [\"torch\"]) """ snake_case_ = create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]} ) self.assertEqual(dummy_files["""torch"""] , UpperCamelCase__ )
721
"""simple docstring""" # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(42) __SCREAMING_SNAKE_CASE : Dict = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE : Dict = 'zero2' __SCREAMING_SNAKE_CASE : List[Any] = 'zero3' __SCREAMING_SNAKE_CASE : int = [ZEROa, ZEROa] def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]: # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param snake_case_ = parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE ) for x in param.args ) ) return f"""{func.__name__}_{param_based_name}""" # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE : Dict = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class __A (snake_case__): '''simple docstring''' @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Union[str, Any] ) ->Any: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Optional[Any] ) ->Optional[Any]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Tuple , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[int] ) ->List[str]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) @require_torch_multi_gpu @parameterized.expand(UpperCAmelCase_ , name_func=UpperCAmelCase_ ) def lowerCAmelCase ( self : Dict , UpperCAmelCase_ : str , UpperCAmelCase_ : List[Any] ) ->Optional[int]: """simple docstring""" self.run_and_check( stage=UpperCAmelCase_ , model=UpperCAmelCase_ , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) def lowerCAmelCase ( self : Optional[int] , UpperCAmelCase_ : Union[str, Any] ) ->Optional[int]: """simple docstring""" pass def lowerCAmelCase ( self : Any , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = models[model] snake_case_ = self.run_trainer( stage=UpperCAmelCase_ , model_name=UpperCAmelCase_ , eval_steps=UpperCAmelCase_ , num_train_epochs=1 , distributed=UpperCAmelCase_ , fpaa=UpperCAmelCase_ , ) self.do_checks(UpperCAmelCase_ ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : str , UpperCAmelCase_ : str , UpperCAmelCase_ : int = 10 , UpperCAmelCase_ : int = 1 , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : bool = True , ) ->List[str]: """simple docstring""" snake_case_ = self.get_auto_remove_tmp_dir("""./xxx""" , after=UpperCAmelCase_ ) snake_case_ = F""" --model_name_or_path {model_name} --dataset_name hf-internal-testing/librispeech_asr_dummy --dataset_config_name clean --train_split_name validation --validation_split_name validation --output_dir {output_dir} --num_train_epochs {str(UpperCAmelCase_ )} --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --evaluation_strategy steps --learning_rate 5e-4 --warmup_steps 8 --orthography timit --preprocessing_num_workers 1 --group_by_length --freeze_feature_extractor --report_to none --save_steps 0 --eval_steps {eval_steps} --report_to none """.split() if fpaa: args.extend(["""--fp16"""] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files snake_case_ = F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split() snake_case_ = [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""] snake_case_ = self.get_launcher(UpperCAmelCase_ ) snake_case_ = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(UpperCAmelCase_ , env=self.get_env() ) return output_dir def lowerCAmelCase ( self : Union[str, Any] , UpperCAmelCase_ : Any=False ) ->Tuple: """simple docstring""" snake_case_ = min(2 , get_gpu_count() ) if distributed else 1 return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()
2
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE_ = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = '''layoutlmv3''' def __init__( self , lowerCamelCase_=5_0_2_6_5 , lowerCamelCase_=7_6_8 , lowerCamelCase_=1_2 , lowerCamelCase_=1_2 , lowerCamelCase_=3_0_7_2 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_1_2 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=1e-5 , lowerCamelCase_=1 , lowerCamelCase_=0 , lowerCamelCase_=2 , lowerCamelCase_=1_0_2_4 , lowerCamelCase_=1_2_8 , lowerCamelCase_=1_2_8 , lowerCamelCase_=True , lowerCamelCase_=3_2 , lowerCamelCase_=1_2_8 , lowerCamelCase_=6_4 , lowerCamelCase_=2_5_6 , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=2_2_4 , lowerCamelCase_=3 , lowerCamelCase_=1_6 , lowerCamelCase_=None , **lowerCamelCase_ , ) -> Optional[Any]: super().__init__( vocab_size=lowerCamelCase_ , hidden_size=lowerCamelCase_ , num_hidden_layers=lowerCamelCase_ , num_attention_heads=lowerCamelCase_ , intermediate_size=lowerCamelCase_ , hidden_act=lowerCamelCase_ , hidden_dropout_prob=lowerCamelCase_ , attention_probs_dropout_prob=lowerCamelCase_ , max_position_embeddings=lowerCamelCase_ , type_vocab_size=lowerCamelCase_ , initializer_range=lowerCamelCase_ , layer_norm_eps=lowerCamelCase_ , pad_token_id=lowerCamelCase_ , bos_token_id=lowerCamelCase_ , eos_token_id=lowerCamelCase_ , **lowerCamelCase_ , ) UpperCamelCase = max_ad_position_embeddings UpperCamelCase = coordinate_size UpperCamelCase = shape_size UpperCamelCase = has_relative_attention_bias UpperCamelCase = rel_pos_bins UpperCamelCase = max_rel_pos UpperCamelCase = has_spatial_attention_bias UpperCamelCase = rel_ad_pos_bins UpperCamelCase = max_rel_ad_pos UpperCamelCase = text_embed UpperCamelCase = visual_embed UpperCamelCase = input_size UpperCamelCase = num_channels UpperCamelCase = patch_size UpperCamelCase = classifier_dropout class snake_case_ ( lowerCamelCase_ ): """simple docstring""" A_ = version.parse('''1.12''' ) @property def UpperCAmelCase__ ( self) -> Mapping[str, Mapping[int, str]]: # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ]) @property def UpperCAmelCase__ ( self) -> float: return 1e-5 @property def UpperCAmelCase__ ( self) -> int: return 1_2 def UpperCAmelCase__ ( self , lowerCamelCase_ , lowerCamelCase_ = -1 , lowerCamelCase_ = -1 , lowerCamelCase_ = False , lowerCamelCase_ = None , lowerCamelCase_ = 3 , lowerCamelCase_ = 4_0 , lowerCamelCase_ = 4_0 , ) -> Mapping[str, Any]: setattr(processor.image_processor , '''apply_ocr''' , lowerCamelCase_) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCamelCase = compute_effective_axis_dimension( lowerCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCamelCase = processor.tokenizer.num_special_tokens_to_add(lowerCamelCase_) UpperCamelCase = compute_effective_axis_dimension( lowerCamelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase_) # Generate dummy inputs according to compute batch and sequence UpperCamelCase = [[''' '''.join([processor.tokenizer.unk_token]) * seq_length]] * batch_size # Generate dummy bounding boxes UpperCamelCase = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) UpperCamelCase = self._generate_dummy_images(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) UpperCamelCase = dict( processor( lowerCamelCase_ , text=lowerCamelCase_ , boxes=lowerCamelCase_ , return_tensors=lowerCamelCase_ , )) return inputs
34
from __future__ import annotations from itertools import permutations from random import randint from timeit import repeat def snake_case ( ): '''simple docstring''' __lowercase = [randint(-1_000 , 1_000 ) for i in range(10 )] __lowercase = randint(-5_000 , 5_000 ) return (arr, r) __UpperCamelCase : Any = make_dataset() def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' for triplet in permutations(lowerCamelCase , 3 ): if sum(lowerCamelCase ) == target: return tuple(sorted(lowerCamelCase ) ) return (0, 0, 0) def snake_case ( lowerCamelCase , lowerCamelCase ): '''simple docstring''' arr.sort() __lowercase = len(lowerCamelCase ) for i in range(n - 1 ): __lowercase , __lowercase = i + 1, n - 1 while left < right: if arr[i] + arr[left] + arr[right] == target: return (arr[i], arr[left], arr[right]) elif arr[i] + arr[left] + arr[right] < target: left += 1 elif arr[i] + arr[left] + arr[right] > target: right -= 1 return (0, 0, 0) def snake_case ( ): '''simple docstring''' __lowercase = """ from __main__ import dataset, triplet_sum1, triplet_sum2 """ __lowercase = """ triplet_sum1(*dataset) """ __lowercase = """ triplet_sum2(*dataset) """ __lowercase = repeat(setup=lowerCamelCase , stmt=lowerCamelCase , repeat=5 , number=10_000 ) __lowercase = repeat(setup=lowerCamelCase , stmt=lowerCamelCase , repeat=5 , number=10_000 ) return (min(lowerCamelCase ), min(lowerCamelCase )) if __name__ == "__main__": from doctest import testmod testmod() __UpperCamelCase : Tuple = solution_times() print(F'''The time for naive implementation is {times[0]}.''') print(F'''The time for optimized implementation is {times[1]}.''')
80
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_tf_available, is_torch_available, ) _UpperCamelCase : Dict = { 'configuration_speech_to_text': ['SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Speech2TextConfig'], 'processing_speech_to_text': ['Speech2TextProcessor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Optional[int] = ['Speech2TextTokenizer'] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : List[Any] = ['Speech2TextFeatureExtractor'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Optional[Any] = [ 'TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSpeech2TextForConditionalGeneration', 'TFSpeech2TextModel', 'TFSpeech2TextPreTrainedModel', ] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : List[str] = [ 'SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Speech2TextForConditionalGeneration', 'Speech2TextModel', 'Speech2TextPreTrainedModel', ] if TYPE_CHECKING: from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig from .processing_speech_to_text import SpeechaTextProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speech_to_text import SpeechaTextTokenizer try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_speech_to_text import ( TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, TFSpeechaTextForConditionalGeneration, TFSpeechaTextModel, TFSpeechaTextPreTrainedModel, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_to_text import ( SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechaTextForConditionalGeneration, SpeechaTextModel, SpeechaTextPreTrainedModel, ) else: import sys _UpperCamelCase : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
118
"""simple docstring""" import json import os import unittest from transformers.models.roc_bert.tokenization_roc_bert import ( VOCAB_FILES_NAMES, RoCBertBasicTokenizer, RoCBertTokenizer, RoCBertWordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class snake_case ( UpperCAmelCase , unittest.TestCase ): __magic_name__ = RoCBertTokenizer __magic_name__ = None __magic_name__ = False __magic_name__ = True __magic_name__ = filter_non_english def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' super().setUp() a : str = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd'] a : List[Any] = {} a : Any = {} for i, value in enumerate(A ): a : Union[str, Any] = i a : str = i a : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] ) a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_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.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer: json.dump(A , A , ensure_ascii=A ) with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer: json.dump(A , A , ensure_ascii=A ) def lowerCamelCase__ ( self : Optional[Any] ): '''simple docstring''' a : int = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) a : Any = tokenizer.tokenize('你好[SEP]你是谁' ) self.assertListEqual(A , ['你', '好', '[SEP]', '你', '是', '谁'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(A ) , [5, 6, 2, 5, 7, 8] ) self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(A ) , [5, 6, 2, 5, 7, 8] ) def lowerCamelCase__ ( self : str ): '''simple docstring''' a : List[str] = RoCBertBasicTokenizer() self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] ) def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' a : Any = RoCBertBasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : int = RoCBertBasicTokenizer(do_lower_case=A , strip_accents=A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] ) def lowerCamelCase__ ( self : str ): '''simple docstring''' a : Union[str, Any] = RoCBertBasicTokenizer(do_lower_case=A , strip_accents=A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def lowerCamelCase__ ( self : str ): '''simple docstring''' a : Any = RoCBertBasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] ) def lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' a : Dict = RoCBertBasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : List[str] = RoCBertBasicTokenizer(do_lower_case=A , strip_accents=A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] ) def lowerCamelCase__ ( self : Dict ): '''simple docstring''' a : List[str] = RoCBertBasicTokenizer(do_lower_case=A , strip_accents=A ) self.assertListEqual( tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] ) def lowerCamelCase__ ( self : str ): '''simple docstring''' a : Optional[Any] = RoCBertBasicTokenizer(do_lower_case=A , never_split=['[UNK]'] ) self.assertListEqual( tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing'] a : str = {} for i, token in enumerate(A ): a : Union[str, Any] = i a : Any = RoCBertWordpieceTokenizer(vocab=A , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] ) self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' self.assertTrue(_is_whitespace(' ' ) ) self.assertTrue(_is_whitespace('\t' ) ) self.assertTrue(_is_whitespace('\r' ) ) self.assertTrue(_is_whitespace('\n' ) ) self.assertTrue(_is_whitespace('\u00A0' ) ) self.assertFalse(_is_whitespace('A' ) ) self.assertFalse(_is_whitespace('-' ) ) def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' self.assertTrue(_is_control('\u0005' ) ) self.assertFalse(_is_control('A' ) ) self.assertFalse(_is_control(' ' ) ) self.assertFalse(_is_control('\t' ) ) self.assertFalse(_is_control('\r' ) ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' self.assertTrue(_is_punctuation('-' ) ) self.assertTrue(_is_punctuation('$' ) ) self.assertTrue(_is_punctuation('`' ) ) self.assertTrue(_is_punctuation('.' ) ) self.assertFalse(_is_punctuation('A' ) ) self.assertFalse(_is_punctuation(' ' ) ) def lowerCamelCase__ ( self : List[str] ): '''simple docstring''' a : List[Any] = self.get_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(A ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) if self.test_rust_tokenizer: a : str = self.get_rust_tokenizer() self.assertListEqual( [rust_tokenizer.tokenize(A ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] ) def lowerCamelCase__ ( self : Dict ): '''simple docstring''' for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a : List[str] = self.rust_tokenizer_class.from_pretrained(A , **A ) a : Any = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' a : str = tokenizer_r.encode_plus( A , return_attention_mask=A , return_token_type_ids=A , return_offsets_mapping=A , add_special_tokens=A , ) a : int = tokenizer_r.do_lower_case if hasattr(A , 'do_lower_case' ) else False a : Tuple = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'A'), ((1, 2), ','), ((3, 5), 'na'), ((5, 6), '##ï'), ((6, 8), '##ve'), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), 'Allen'), ((2_1, 2_3), '##NL'), ((2_3, 2_4), '##P'), ((2_5, 3_3), 'sentence'), ((3_3, 3_4), '.'), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), 'a'), ((1, 2), ','), ((3, 8), 'naive'), ((9, 1_5), tokenizer_r.mask_token), ((1_6, 2_1), 'allen'), ((2_1, 2_3), '##nl'), ((2_3, 2_4), '##p'), ((2_5, 3_3), 'sentence'), ((3_3, 3_4), '.'), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) ) self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] ) def lowerCamelCase__ ( self : Optional[int] ): '''simple docstring''' a : Union[str, Any] = ['的', '人', '有'] a : Tuple = ''.join(A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): a : Optional[int] = True a : Any = self.tokenizer_class.from_pretrained(A , **A ) a : Optional[Any] = self.rust_tokenizer_class.from_pretrained(A , **A ) a : Optional[Any] = tokenizer_p.encode(A , add_special_tokens=A ) a : Dict = tokenizer_r.encode(A , add_special_tokens=A ) a : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(A ) a : Tuple = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(A , A ) self.assertListEqual(A , A ) a : Dict = False a : Any = self.rust_tokenizer_class.from_pretrained(A , **A ) a : List[Any] = self.tokenizer_class.from_pretrained(A , **A ) a : Optional[int] = tokenizer_r.encode(A , add_special_tokens=A ) a : List[str] = tokenizer_p.encode(A , add_special_tokens=A ) a : Union[str, Any] = tokenizer_r.convert_ids_to_tokens(A ) a : Tuple = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that only the first Chinese character is not preceded by "##". a : List[str] = [ F'''##{token}''' if idx != 0 else token for idx, token in enumerate(A ) ] self.assertListEqual(A , A ) self.assertListEqual(A , A ) @slow def lowerCamelCase__ ( self : int ): '''simple docstring''' a : Dict = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file ) a : List[str] = tokenizer.encode('你好' , add_special_tokens=A ) a : int = tokenizer.encode('你是谁' , add_special_tokens=A ) a : Any = tokenizer.build_inputs_with_special_tokens(A ) a : Tuple = tokenizer.build_inputs_with_special_tokens(A , A ) assert encoded_sentence == [1] + text + [2] assert encoded_pair == [1] + text + [2] + text_a + [2] def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : Optional[int] = self.get_tokenizers(do_lower_case=A ) for tokenizer in tokenizers: with self.subTest(F'''{tokenizer.__class__.__name__}''' ): a : Dict = '你好,你是谁' a : List[str] = tokenizer.tokenize(A ) a : str = tokenizer.convert_tokens_to_ids(A ) a : str = tokenizer.convert_tokens_to_shape_ids(A ) a : Union[str, Any] = tokenizer.convert_tokens_to_pronunciation_ids(A ) a : Any = tokenizer.prepare_for_model( A , A , A , add_special_tokens=A ) a : Union[str, Any] = tokenizer.encode_plus(A , add_special_tokens=A ) self.assertEqual(A , A )
118
1
'''simple docstring''' def lowerCAmelCase (__A): """simple docstring""" return sum(i for i in range(1 , number // 2 + 1) if number % i == 0) == number if __name__ == "__main__": print("Program to check whether a number is a Perfect number or not...") lowercase_ = int(input("Enter number: ").strip()) print(F"""{number} is {'' if perfect(number) else 'not '}a Perfect Number.""")
11
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __A ( A , A , unittest.TestCase ): '''simple docstring''' __lowerCamelCase : List[Any] = IFInpaintingSuperResolutionPipeline __lowerCamelCase : Tuple = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'width', 'height'} __lowerCamelCase : Optional[Any] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({'original_image'} ) __lowerCamelCase : str = PipelineTesterMixin.required_optional_params - {'latents'} def a__ (self ) -> List[Any]: """simple docstring""" return self._get_superresolution_dummy_components() def a__ (self , A , A=0 ) -> List[Any]: """simple docstring""" if str(A ).startswith('''mps''' ): _a = torch.manual_seed(A ) else: _a = torch.Generator(device=A ).manual_seed(A ) _a = floats_tensor((1, 3, 16, 16) , rng=random.Random(A ) ).to(A ) _a = floats_tensor((1, 3, 32, 32) , rng=random.Random(A ) ).to(A ) _a = floats_tensor((1, 3, 32, 32) , rng=random.Random(A ) ).to(A ) _a = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''original_image''': original_image, '''mask_image''': mask_image, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def a__ (self ) -> Optional[int]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def a__ (self ) -> str: """simple docstring""" self._test_save_load_optional_components() @unittest.skipIf(torch_device != '''cuda''' , reason='''float16 requires CUDA''' ) def a__ (self ) -> str: """simple docstring""" super().test_save_load_floataa(expected_max_diff=1E-1 ) def a__ (self ) -> Tuple: """simple docstring""" self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def a__ (self ) -> Union[str, Any]: """simple docstring""" self._test_save_load_local() def a__ (self ) -> Any: """simple docstring""" self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
11
1
def _lowerCAmelCase ( UpperCamelCase__: list , UpperCamelCase__: int = 0 ) -> list: """simple docstring""" A = length or len(UpperCamelCase__ ) A = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: A , A = list_data[i + 1], list_data[i] A = True return list_data if not swapped else bubble_sort(UpperCamelCase__ , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
718
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _lowerCAmelCase ( UpperCamelCase__: Any ) -> Tuple: """simple docstring""" def wrapper(*UpperCamelCase__: Union[str, Any] , **UpperCamelCase__: List[str] ): A = timeit.default_timer() A = func(*UpperCamelCase__ , **UpperCamelCase__ ) A = timeit.default_timer() - starttime return delta A = func.__name__ return wrapper def _lowerCAmelCase ( UpperCamelCase__: dict , UpperCamelCase__: List[str]=1_00 , UpperCamelCase__: int=None ) -> Any: """simple docstring""" A = [] A = seq_shapes or {} for i in range(UpperCamelCase__ ): A = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(UpperCamelCase__ , _ArrayXD ): A = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(UpperCamelCase__ , datasets.Value ): if v.dtype == "string": A = """The small grey turtle was surprisingly fast when challenged.""" else: A = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(UpperCamelCase__ , datasets.Sequence ): while isinstance(UpperCamelCase__ , datasets.Sequence ): A = v.feature A = seq_shapes[k] A = np.random.rand(*UpperCamelCase__ ).astype(v.dtype ) A = data dummy_data.append((i, example) ) return dummy_data def _lowerCAmelCase ( UpperCamelCase__: int , UpperCamelCase__: Union[str, Any] , UpperCamelCase__: List[str]=1_00 , UpperCamelCase__: str=None ) -> Optional[int]: """simple docstring""" A = generate_examples(UpperCamelCase__ , num_examples=UpperCamelCase__ , seq_shapes=UpperCamelCase__ ) with ArrowWriter(features=UpperCamelCase__ , path=UpperCamelCase__ ) as writer: for key, record in dummy_data: A = features.encode_example(UpperCamelCase__ ) writer.write(UpperCamelCase__ ) A , A = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.' ) A = datasets.Dataset.from_file(filename=UpperCamelCase__ , info=datasets.DatasetInfo(features=UpperCamelCase__ ) ) return dataset
546
0
from __future__ import annotations def a__ ( A__, A__ ): SCREAMING_SNAKE_CASE_ : list[list[int]] = [] SCREAMING_SNAKE_CASE_ : list[int] = [] SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 SCREAMING_SNAKE_CASE_ : int = sum(A__ ) create_state_space_tree(A__, A__, A__, A__, A__, A__ ) return result def a__ ( A__, A__, A__, A__, A__, A__, ): if sum(A__ ) > max_sum or (remaining_nums_sum + sum(A__ )) < max_sum: return if sum(A__ ) == max_sum: result.append(A__ ) return for index in range(A__, len(A__ ) ): create_state_space_tree( A__, A__, index + 1, [*path, nums[index]], A__, remaining_nums_sum - nums[index], ) lowerCAmelCase__ : List[str] =[3, 34, 4, 12, 5, 2] lowerCAmelCase__ : str =9 lowerCAmelCase__ : Optional[int] =generate_sum_of_subsets_soln(nums, max_sum) print(*result)
101
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class A__: """simple docstring""" def __init__( self , _lowercase , _lowercase=13 , _lowercase=7 , _lowercase=True , _lowercase=True , _lowercase=False , _lowercase=True , _lowercase=99 , _lowercase=32 , _lowercase=5 , _lowercase=4 , _lowercase=37 , _lowercase="gelu" , _lowercase=0.1 , _lowercase=0.1 , _lowercase=512 , _lowercase=16 , _lowercase=2 , _lowercase=0.0_2 , _lowercase=3 , _lowercase=4 , _lowercase=None , ) -> Tuple: a_ : Union[str, Any] = parent a_ : int = batch_size a_ : int = seq_length a_ : int = is_training a_ : List[Any] = use_input_mask a_ : str = use_token_type_ids a_ : List[str] = use_labels a_ : List[Any] = vocab_size a_ : Dict = hidden_size a_ : List[Any] = num_hidden_layers a_ : str = num_attention_heads a_ : str = intermediate_size a_ : Optional[int] = hidden_act a_ : Optional[int] = hidden_dropout_prob a_ : int = attention_probs_dropout_prob a_ : List[str] = max_position_embeddings a_ : Optional[Any] = type_vocab_size a_ : Any = type_sequence_label_size a_ : List[Any] = initializer_range a_ : List[str] = num_labels a_ : Union[str, Any] = num_choices a_ : Dict = scope def UpperCamelCase__ ( self ) -> Any: a_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a_ : Union[str, Any] = None if self.use_input_mask: a_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) a_ : List[Any] = None if self.use_token_type_ids: a_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a_ : Union[str, Any] = None a_ : Dict = None a_ : Any = None if self.use_labels: a_ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a_ : int = ids_tensor([self.batch_size] , self.num_choices ) a_ : Optional[int] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self ) -> Any: return OpenLlamaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowercase , initializer_range=self.initializer_range , use_stable_embedding=_lowercase , ) def UpperCamelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase ) -> Dict: a_ : Optional[Any] = OpenLlamaModel(config=_lowercase ) model.to(_lowercase ) model.eval() a_ : List[Any] = model(_lowercase , attention_mask=_lowercase ) a_ : Optional[Any] = model(_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ) -> Union[str, Any]: a_ : int = True a_ : Union[str, Any] = OpenLlamaModel(_lowercase ) model.to(_lowercase ) model.eval() a_ : Optional[int] = model( _lowercase , attention_mask=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , ) a_ : Any = model( _lowercase , attention_mask=_lowercase , encoder_hidden_states=_lowercase , ) a_ : Optional[int] = model(_lowercase , attention_mask=_lowercase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ) -> Any: a_ : Dict = OpenLlamaForCausalLM(config=_lowercase ) model.to(_lowercase ) model.eval() a_ : int = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase__ ( self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , ) -> List[str]: a_ : Dict = True a_ : Optional[int] = True a_ : Dict = OpenLlamaForCausalLM(config=_lowercase ) model.to(_lowercase ) model.eval() # first forward pass a_ : List[str] = model( _lowercase , attention_mask=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , use_cache=_lowercase , ) a_ : Optional[Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids a_ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) a_ : Union[str, Any] = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and a_ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) a_ : Any = torch.cat([input_mask, next_mask] , dim=-1 ) a_ : Optional[int] = model( _lowercase , attention_mask=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , output_hidden_states=_lowercase , )["""hidden_states"""][0] a_ : Dict = model( _lowercase , attention_mask=_lowercase , encoder_hidden_states=_lowercase , encoder_attention_mask=_lowercase , past_key_values=_lowercase , output_hidden_states=_lowercase , )["""hidden_states"""][0] # select random slice a_ : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() a_ : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() a_ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_lowercase , _lowercase , atol=1e-3 ) ) def UpperCamelCase__ ( self ) -> Optional[Any]: a_ : Any = self.prepare_config_and_inputs() ( ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ( a_ ) , ) : Union[str, Any] = config_and_inputs a_ : Tuple = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class A__(a_, a_, a_, unittest.TestCase ): """simple docstring""" _A : Tuple = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) _A : int = (OpenLlamaForCausalLM,) if is_torch_available() else () _A : Optional[int] = ( { '''feature-extraction''': OpenLlamaModel, '''text-classification''': OpenLlamaForSequenceClassification, '''text-generation''': OpenLlamaForCausalLM, '''zero-shot''': OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) _A : Tuple = False _A : Any = False def UpperCamelCase__ ( self ) -> List[str]: a_ : Optional[int] = OpenLlamaModelTester(self ) a_ : Optional[int] = ConfigTester(self , config_class=_lowercase , hidden_size=37 ) def UpperCamelCase__ ( self ) -> Any: self.config_tester.run_common_tests() def UpperCamelCase__ ( self ) -> Optional[Any]: a_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowercase ) def UpperCamelCase__ ( self ) -> Tuple: a_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a_ : Dict = type self.model_tester.create_and_check_model(*_lowercase ) def UpperCamelCase__ ( self ) -> Union[str, Any]: a_ , a_ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() a_ : Any = 3 a_ : List[str] = input_dict["""input_ids"""] a_ : List[str] = input_ids.ne(1 ).to(_lowercase ) a_ : int = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) a_ : int = OpenLlamaForSequenceClassification(_lowercase ) model.to(_lowercase ) model.eval() a_ : Tuple = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCamelCase__ ( self ) -> Optional[Any]: a_ , a_ : Any = self.model_tester.prepare_config_and_inputs_for_common() a_ : Union[str, Any] = 3 a_ : List[Any] = """single_label_classification""" a_ : Dict = input_dict["""input_ids"""] a_ : int = input_ids.ne(1 ).to(_lowercase ) a_ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) a_ : Any = OpenLlamaForSequenceClassification(_lowercase ) model.to(_lowercase ) model.eval() a_ : Any = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCamelCase__ ( self ) -> Tuple: a_ , a_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() a_ : Any = 3 a_ : List[str] = """multi_label_classification""" a_ : Dict = input_dict["""input_ids"""] a_ : Any = input_ids.ne(1 ).to(_lowercase ) a_ : List[Any] = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) a_ : Optional[int] = OpenLlamaForSequenceClassification(_lowercase ) model.to(_lowercase ) model.eval() a_ : int = model(_lowercase , attention_mask=_lowercase , labels=_lowercase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip("""Open-Llama buffers include complex numbers, which breaks this test""" ) def UpperCamelCase__ ( self ) -> Tuple: pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def UpperCamelCase__ ( self , _lowercase ) -> str: a_ , a_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() a_ : List[Any] = ids_tensor([1, 10] , config.vocab_size ) a_ : str = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights a_ : Union[str, Any] = OpenLlamaModel(_lowercase ) original_model.to(_lowercase ) original_model.eval() a_ : Union[str, Any] = original_model(_lowercase ).last_hidden_state a_ : str = original_model(_lowercase ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights a_ : int = {"""type""": scaling_type, """factor""": 1_0.0} a_ : Union[str, Any] = OpenLlamaModel(_lowercase ) scaled_model.to(_lowercase ) scaled_model.eval() a_ : Optional[int] = scaled_model(_lowercase ).last_hidden_state a_ : Tuple = scaled_model(_lowercase ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(_lowercase , _lowercase , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(_lowercase , _lowercase , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(_lowercase , _lowercase , atol=1e-5 ) )
540
0
import unittest from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available from transformers.pipelines import pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectrona, require_pytesseract, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class A : @staticmethod def SCREAMING_SNAKE_CASE__ ( *UpperCamelCase__, **UpperCamelCase__ ): """simple docstring""" pass def __UpperCamelCase ( _A ): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. _A = ( '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png''' ) @is_pipeline_test @require_torch @require_vision class A ( unittest.TestCase ): __snake_case = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = pipeline( '''document-question-answering''', model=UpperCamelCase__, tokenizer=UpperCamelCase__, image_processor=UpperCamelCase__ ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = list(zip(*apply_tesseract(load_image(UpperCamelCase__ ), UpperCamelCase__, '''''' ) ) ) lowerCAmelCase_ = '''What is the placebo?''' lowerCAmelCase_ = [ { '''image''': load_image(UpperCamelCase__ ), '''question''': question, }, { '''image''': image, '''question''': question, }, { '''image''': image, '''question''': question, '''word_boxes''': word_boxes, }, ] return dqa_pipeline, examples def SCREAMING_SNAKE_CASE__ ( self, UpperCamelCase__, UpperCamelCase__ ): """simple docstring""" lowerCAmelCase_ = dqa_pipeline(UpperCamelCase__, top_k=2 ) self.assertEqual( UpperCamelCase__, [ [ {'''score''': ANY(UpperCamelCase__ ), '''answer''': ANY(UpperCamelCase__ ), '''start''': ANY(UpperCamelCase__ ), '''end''': ANY(UpperCamelCase__ )}, {'''score''': ANY(UpperCamelCase__ ), '''answer''': ANY(UpperCamelCase__ ), '''start''': ANY(UpperCamelCase__ ), '''end''': ANY(UpperCamelCase__ )}, ] ] * 3, ) @require_torch @require_detectrona @require_pytesseract def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = pipeline('''document-question-answering''', model='''hf-internal-testing/tiny-random-layoutlmv2''' ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''How many cats are there?''' lowerCAmelCase_ = [ {'''score''': 0.0_001, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39}, {'''score''': 0.0_001, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40}, ] lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual(nested_simplify(UpperCamelCase__, decimals=4 ), UpperCamelCase__ ) lowerCAmelCase_ = dqa_pipeline({'''image''': image, '''question''': question}, top_k=2 ) self.assertEqual(nested_simplify(UpperCamelCase__, decimals=4 ), UpperCamelCase__ ) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably lowerCAmelCase_ = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual(UpperCamelCase__, [] ) # We can optionnally pass directly the words and bounding boxes lowerCAmelCase_ = '''./tests/fixtures/tests_samples/COCO/000000039769.png''' lowerCAmelCase_ = [] lowerCAmelCase_ = [] lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, words=UpperCamelCase__, boxes=UpperCamelCase__, top_k=2 ) self.assertEqual(UpperCamelCase__, [] ) @slow @require_torch @require_detectrona @require_pytesseract def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = pipeline( '''document-question-answering''', model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''', revision='''9977165''', ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''What is the invoice number?''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) lowerCAmelCase_ = dqa_pipeline({'''image''': image, '''question''': question}, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) lowerCAmelCase_ = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}], top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ [ {'''score''': 0.9_944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ] * 2, ) @slow @require_torch @require_detectrona @require_pytesseract def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = pipeline( '''document-question-answering''', model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa''', revision='''9977165''', max_seq_len=50, ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''What is the invoice number?''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9_948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) lowerCAmelCase_ = dqa_pipeline({'''image''': image, '''question''': question}, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9_948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) lowerCAmelCase_ = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}], top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ [ {'''score''': 0.9_974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, {'''score''': 0.9_948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2, ) @slow @require_torch @require_pytesseract @require_vision def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''', revision='''3dc6de3''', add_prefix_space=UpperCamelCase__ ) lowerCAmelCase_ = pipeline( '''document-question-answering''', model='''impira/layoutlm-document-qa''', tokenizer=UpperCamelCase__, revision='''3dc6de3''', ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''What is the invoice number?''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.4_251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ], ) lowerCAmelCase_ = dqa_pipeline({'''image''': image, '''question''': question}, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.4_251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ], ) lowerCAmelCase_ = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}], top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ [ {'''score''': 0.4_251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ] ] * 2, ) lowerCAmelCase_ = list(zip(*apply_tesseract(load_image(UpperCamelCase__ ), UpperCamelCase__, '''''' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase_ = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.4_251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.0_819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23}, ], ) @slow @require_torch @require_pytesseract @require_vision def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = AutoTokenizer.from_pretrained( '''impira/layoutlm-document-qa''', revision='''3dc6de3''', add_prefix_space=UpperCamelCase__ ) lowerCAmelCase_ = pipeline( '''document-question-answering''', model='''impira/layoutlm-document-qa''', tokenizer=UpperCamelCase__, revision='''3dc6de3''', max_seq_len=50, ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''What is the invoice number?''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9_998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) lowerCAmelCase_ = dqa_pipeline( [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}], top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ [ {'''score''': 0.9_999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9_998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ] ] * 2, ) lowerCAmelCase_ = list(zip(*apply_tesseract(load_image(UpperCamelCase__ ), UpperCamelCase__, '''''' ) ) ) # This model should also work if `image` is set to None lowerCAmelCase_ = dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}, top_k=2 ) self.assertEqual( nested_simplify(UpperCamelCase__, decimals=4 ), [ {'''score''': 0.9_999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, {'''score''': 0.9_998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16}, ], ) @slow @require_torch def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" lowerCAmelCase_ = pipeline( '''document-question-answering''', model='''naver-clova-ix/donut-base-finetuned-docvqa''', tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' ), feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa''', ) lowerCAmelCase_ = INVOICE_URL lowerCAmelCase_ = '''What is the invoice number?''' lowerCAmelCase_ = dqa_pipeline(image=UpperCamelCase__, question=UpperCamelCase__, top_k=2 ) self.assertEqual(nested_simplify(UpperCamelCase__, decimals=4 ), [{'''answer''': '''us-001'''}] ) @require_tf @unittest.skip('''Document question answering not implemented in TF''' ) def SCREAMING_SNAKE_CASE__ ( self ): """simple docstring""" pass
720
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available _A = { '''configuration_maskformer''': ['''MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MaskFormerConfig'''], '''configuration_maskformer_swin''': ['''MaskFormerSwinConfig'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['''MaskFormerFeatureExtractor'''] _A = ['''MaskFormerImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ '''MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''', '''MaskFormerForInstanceSegmentation''', '''MaskFormerModel''', '''MaskFormerPreTrainedModel''', ] _A = [ '''MaskFormerSwinBackbone''', '''MaskFormerSwinModel''', '''MaskFormerSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_maskformer import MASKFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, MaskFormerConfig from .configuration_maskformer_swin import MaskFormerSwinConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_maskformer import MaskFormerFeatureExtractor from .image_processing_maskformer import MaskFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_maskformer import ( MASKFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, MaskFormerForInstanceSegmentation, MaskFormerModel, MaskFormerPreTrainedModel, ) from .modeling_maskformer_swin import ( MaskFormerSwinBackbone, MaskFormerSwinModel, MaskFormerSwinPreTrainedModel, ) else: import sys _A = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
325
0
'''simple docstring''' import math import tensorflow as tf from packaging import version def lowercase_ ( __A : str ) -> List[Any]: """simple docstring""" lowercase : int =tf.convert_to_tensor(__A ) lowercase : Dict =0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def lowercase_ ( __A : Any ) -> int: """simple docstring""" lowercase : Optional[Any] =tf.convert_to_tensor(__A ) lowercase : Tuple =tf.cast(math.pi , x.dtype ) lowercase : List[Any] =tf.cast(0.044715 , x.dtype ) lowercase : Optional[Any] =0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__A , 3 )) )) return x * cdf def lowercase_ ( __A : List[str] ) -> Optional[Any]: """simple docstring""" lowercase : Optional[int] =tf.convert_to_tensor(__A ) return x * tf.tanh(tf.math.softplus(__A ) ) def lowercase_ ( __A : Dict ) -> Union[str, Any]: """simple docstring""" lowercase : Union[str, Any] =tf.convert_to_tensor(__A ) lowercase : Tuple =tf.cast(0.044715 , x.dtype ) lowercase : Any =tf.cast(0.7978845608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowercase_ ( __A : Optional[Any] ) -> Dict: """simple docstring""" lowercase : List[str] =tf.convert_to_tensor(__A ) lowercase : Optional[int] =tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowercase_ ( __A : Dict ) -> Union[str, Any]: """simple docstring""" return tf.clip_by_value(_gelu(__A ) , -1_0 , 1_0 ) def lowercase_ ( __A : Optional[Any] , __A : int=-1 ) -> Tuple: """simple docstring""" lowercase , lowercase : List[Any] =tf.split(__A , 2 , axis=__A ) return a * tf.math.sigmoid(__A ) if version.parse(tf.version.VERSION) >= version.parse('2.4'): def lowercase_ ( __A : str ) -> Optional[int]: """simple docstring""" return tf.keras.activations.gelu(__A , approximate=__A ) SCREAMING_SNAKE_CASE = tf.keras.activations.gelu SCREAMING_SNAKE_CASE = approximate_gelu_wrap else: SCREAMING_SNAKE_CASE = _gelu SCREAMING_SNAKE_CASE = _gelu_new SCREAMING_SNAKE_CASE = { 'gelu': gelu, 'gelu_10': gelu_aa, 'gelu_fast': gelu_fast, 'gelu_new': gelu_new, 'glu': glu, 'mish': mish, 'quick_gelu': quick_gelu, 'relu': tf.keras.activations.relu, 'sigmoid': tf.keras.activations.sigmoid, 'silu': tf.keras.activations.swish, 'swish': tf.keras.activations.swish, 'tanh': tf.keras.activations.tanh, } def lowercase_ ( __A : Optional[int] ) -> Optional[int]: """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(F'function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}' )
94
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch UpperCAmelCase : Optional[Any] = True except ImportError: UpperCAmelCase : Optional[int] = False try: from torch.hub import _get_torch_home UpperCAmelCase : Union[str, Any] = _get_torch_home() except ImportError: UpperCAmelCase : Dict = os.path.expanduser( os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')) ) UpperCAmelCase : Any = os.path.join(torch_cache_home, 'transformers') UpperCAmelCase : int = 'https://cdn.huggingface.co' UpperCAmelCase : Dict = 'https://s3.amazonaws.com/models.huggingface.co/bert' UpperCAmelCase : str = '/'.join(str(Path(__file__).resolve()).split('/')[:-1]) UpperCAmelCase : List[str] = os.path.join(PATH, 'config.yaml') UpperCAmelCase : int = os.path.join(PATH, 'attributes.txt') UpperCAmelCase : Dict = os.path.join(PATH, 'objects.txt') UpperCAmelCase : str = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path) UpperCAmelCase : List[str] = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE) UpperCAmelCase : Optional[Any] = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE) UpperCAmelCase : Tuple = 'pytorch_model.bin' UpperCAmelCase : List[Any] = 'config.yaml' def lowerCamelCase ( _UpperCamelCase : Any=OBJECTS , _UpperCamelCase : str=ATTRIBUTES ) -> Optional[Any]: '''simple docstring''' __UpperCAmelCase : Dict = [] with open(_UpperCamelCase ) as f: for object in f.readlines(): vg_classes.append(object.split(""",""" )[0].lower().strip() ) __UpperCAmelCase : Any = [] with open(_UpperCamelCase ) as f: for object in f.readlines(): vg_attrs.append(object.split(""",""" )[0].lower().strip() ) return vg_classes, vg_attrs def lowerCamelCase ( _UpperCamelCase : int ) -> Any: '''simple docstring''' __UpperCAmelCase : Tuple = OrderedDict() with open(_UpperCamelCase , """rb""" ) as f: __UpperCAmelCase : List[str] = pkl.load(_UpperCamelCase )["""model"""] for k in copy.deepcopy(list(ckp.keys() ) ): __UpperCAmelCase : List[str] = ckp.pop(_UpperCamelCase ) if isinstance(_UpperCamelCase , np.ndarray ): __UpperCAmelCase : List[Any] = torch.tensor(_UpperCamelCase ) else: assert isinstance(_UpperCamelCase , torch.tensor ), type(_UpperCamelCase ) __UpperCAmelCase : str = v return r class lowerCamelCase__ : """simple docstring""" __a = {} def __init__( self : Optional[Any] , UpperCamelCase : dict , UpperCamelCase : str = "root" , UpperCamelCase : Tuple=0 ): '''simple docstring''' __UpperCAmelCase : List[Any] = name __UpperCAmelCase : Optional[Any] = level __UpperCAmelCase : List[str] = {} for k, v in dictionary.items(): if v is None: raise ValueError() __UpperCAmelCase : Any = copy.deepcopy(UpperCamelCase ) __UpperCAmelCase : int = copy.deepcopy(UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ): __UpperCAmelCase : Any = Config(UpperCamelCase , name=UpperCamelCase , level=level + 1 ) __UpperCAmelCase : List[str] = v setattr(self , UpperCamelCase , UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = d def __repr__( self : Dict ): '''simple docstring''' return str(list((self._pointer.keys()) ) ) def __setattr__( self : str , UpperCamelCase : int , UpperCamelCase : List[Any] ): '''simple docstring''' __UpperCAmelCase : Tuple = val __UpperCAmelCase : Optional[int] = val __UpperCAmelCase : Union[str, Any] = key.split(""".""" ) __UpperCAmelCase : Any = len(UpperCamelCase ) - 1 __UpperCAmelCase : Tuple = self._pointer if len(UpperCamelCase ) > 1: for i, l in enumerate(UpperCamelCase ): if hasattr(self , UpperCamelCase ) and isinstance(getattr(self , UpperCamelCase ) , UpperCamelCase ): setattr(getattr(self , UpperCamelCase ) , """.""".join(levels[i:] ) , UpperCamelCase ) if l == last_level: __UpperCAmelCase : List[str] = val else: __UpperCAmelCase : Dict = pointer[l] def lowerCamelCase__ ( self : str ): '''simple docstring''' return self._pointer def lowerCamelCase__ ( self : Any , UpperCamelCase : Dict , UpperCamelCase : Any ): '''simple docstring''' with open(f'''{file_name}''' , """w""" ) as stream: dump(UpperCamelCase , UpperCamelCase ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase : Optional[int] , UpperCamelCase : Dict ): '''simple docstring''' with open(f'''{file_name}''' , """w""" ) as stream: json.dump(UpperCamelCase , UpperCamelCase ) @staticmethod def lowerCamelCase__ ( UpperCamelCase : Any ): '''simple docstring''' with open(UpperCamelCase ) as stream: __UpperCAmelCase : List[Any] = load(UpperCamelCase , Loader=UpperCamelCase ) return data def __str__( self : Dict ): '''simple docstring''' __UpperCAmelCase : Union[str, Any] = """ """ if self._name != "root": __UpperCAmelCase : Tuple = f'''{t * (self._level-1)}{self._name}:\n''' else: __UpperCAmelCase : List[str] = """""" __UpperCAmelCase : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(UpperCamelCase , UpperCamelCase ): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(UpperCamelCase ).__name__})\n''' __UpperCAmelCase : Optional[Any] = level return r[:-1] @classmethod def lowerCamelCase__ ( cls : Dict , UpperCamelCase : str , **UpperCamelCase : Optional[Any] ): '''simple docstring''' __UpperCAmelCase ,__UpperCAmelCase : Any = cls.get_config_dict(UpperCamelCase , **UpperCamelCase ) return cls(UpperCamelCase ) @classmethod def lowerCamelCase__ ( cls : List[Any] , UpperCamelCase : str , **UpperCamelCase : Any ): '''simple docstring''' __UpperCAmelCase : List[str] = kwargs.pop("""cache_dir""" , UpperCamelCase ) __UpperCAmelCase : str = kwargs.pop("""force_download""" , UpperCamelCase ) __UpperCAmelCase : Optional[int] = kwargs.pop("""resume_download""" , UpperCamelCase ) __UpperCAmelCase : Optional[Any] = kwargs.pop("""proxies""" , UpperCamelCase ) __UpperCAmelCase : int = kwargs.pop("""local_files_only""" , UpperCamelCase ) if os.path.isdir(UpperCamelCase ): __UpperCAmelCase : str = os.path.join(UpperCamelCase , UpperCamelCase ) elif os.path.isfile(UpperCamelCase ) or is_remote_url(UpperCamelCase ): __UpperCAmelCase : List[str] = pretrained_model_name_or_path else: __UpperCAmelCase : List[str] = hf_bucket_url(UpperCamelCase , filename=UpperCamelCase , use_cdn=UpperCamelCase ) try: # Load from URL or cache if already cached __UpperCAmelCase : str = cached_path( UpperCamelCase , cache_dir=UpperCamelCase , force_download=UpperCamelCase , proxies=UpperCamelCase , resume_download=UpperCamelCase , local_files_only=UpperCamelCase , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __UpperCAmelCase : Optional[Any] = Config.load_yaml(UpperCamelCase ) except EnvironmentError: __UpperCAmelCase : Any = """Can't load config for""" raise EnvironmentError(UpperCamelCase ) if resolved_config_file == config_file: print("""loading configuration file from path""" ) else: print("""loading configuration file cache""" ) return Config.load_yaml(UpperCamelCase ), kwargs def lowerCamelCase ( _UpperCamelCase : Optional[Any] ) -> int: '''simple docstring''' __UpperCAmelCase : str = torch.load("""dump.pt""" , map_location=in_tensor.device ) __UpperCAmelCase : Dict = in_tensor.numpy() __UpperCAmelCase : int = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(_UpperCamelCase , _UpperCamelCase , rtol=0.01 , atol=0.1 ), ( f'''{sum([1 for x in np.isclose(_UpperCamelCase , _UpperCamelCase , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*1_0_0:.4f} %''' " element-wise mismatch" ) raise Exception("""tensors are all good""" ) # Hugging face functions below def lowerCamelCase ( _UpperCamelCase : str ) -> int: '''simple docstring''' __UpperCAmelCase : List[Any] = urlparse(_UpperCamelCase ) return parsed.scheme in ("http", "https") def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : Tuple=True ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[Any] = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __UpperCAmelCase : Optional[int] = """/""" not in model_id if legacy_format: return f'''{endpoint}/{model_id}-{filename}''' else: return f'''{endpoint}/{model_id}/{filename}''' def lowerCamelCase ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Any , _UpperCamelCase : int=None , _UpperCamelCase : Optional[Any]=0 , _UpperCamelCase : Dict=None , ) -> int: '''simple docstring''' __UpperCAmelCase : List[str] = """python/{}""".format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(_UpperCamelCase , _UpperCamelCase ): ua += "; " + "; ".join("""{}/{}""".format(_UpperCamelCase , _UpperCamelCase ) for k, v in user_agent.items() ) elif isinstance(_UpperCamelCase , _UpperCamelCase ): ua += "; " + user_agent __UpperCAmelCase : int = {"""user-agent""": ua} if resume_size > 0: __UpperCAmelCase : Dict = """bytes=%d-""" % (resume_size,) __UpperCAmelCase : List[str] = requests.get(_UpperCamelCase , stream=_UpperCamelCase , proxies=_UpperCamelCase , headers=_UpperCamelCase ) if response.status_code == 4_1_6: # Range not satisfiable return __UpperCAmelCase : Dict = response.headers.get("""Content-Length""" ) __UpperCAmelCase : List[Any] = resume_size + int(_UpperCamelCase ) if content_length is not None else None __UpperCAmelCase : List[str] = tqdm( unit="""B""" , unit_scale=_UpperCamelCase , total=_UpperCamelCase , initial=_UpperCamelCase , desc="""Downloading""" , ) for chunk in response.iter_content(chunk_size=1_0_2_4 ): if chunk: # filter out keep-alive new chunks progress.update(len(_UpperCamelCase ) ) temp_file.write(_UpperCamelCase ) progress.close() def lowerCamelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[int]=None , _UpperCamelCase : Optional[Any]=False , _UpperCamelCase : Dict=None , _UpperCamelCase : List[str]=1_0 , _UpperCamelCase : Optional[Any]=False , _UpperCamelCase : Dict=None , _UpperCamelCase : int=False , ) -> Optional[Any]: '''simple docstring''' if cache_dir is None: __UpperCAmelCase : List[Any] = TRANSFORMERS_CACHE if isinstance(_UpperCamelCase , _UpperCamelCase ): __UpperCAmelCase : Dict = str(_UpperCamelCase ) os.makedirs(_UpperCamelCase , exist_ok=_UpperCamelCase ) __UpperCAmelCase : Optional[int] = None if not local_files_only: try: __UpperCAmelCase : Union[str, Any] = requests.head(_UpperCamelCase , allow_redirects=_UpperCamelCase , proxies=_UpperCamelCase , timeout=_UpperCamelCase ) if response.status_code == 2_0_0: __UpperCAmelCase : Dict = response.headers.get("""ETag""" ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __UpperCAmelCase : Optional[Any] = url_to_filename(_UpperCamelCase , _UpperCamelCase ) # get cache path to put the file __UpperCAmelCase : Dict = os.path.join(_UpperCamelCase , _UpperCamelCase ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(_UpperCamelCase ): return cache_path else: __UpperCAmelCase : List[Any] = [ file for file in fnmatch.filter(os.listdir(_UpperCamelCase ) , filename + """.*""" ) if not file.endswith(""".json""" ) and not file.endswith(""".lock""" ) ] if len(_UpperCamelCase ) > 0: return os.path.join(_UpperCamelCase , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( """Cannot find the requested files in the cached path and outgoing traffic has been""" """ disabled. To enable model look-ups and downloads online, set 'local_files_only'""" """ to False.""" ) return None # From now on, etag is not None. if os.path.exists(_UpperCamelCase ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __UpperCAmelCase : Optional[Any] = cache_path + """.lock""" with FileLock(_UpperCamelCase ): # If the download just completed while the lock was activated. if os.path.exists(_UpperCamelCase ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __UpperCAmelCase : Optional[Any] = cache_path + """.incomplete""" @contextmanager def _resumable_file_manager(): with open(_UpperCamelCase , """a+b""" ) as f: yield f __UpperCAmelCase : Dict = _resumable_file_manager if os.path.exists(_UpperCamelCase ): __UpperCAmelCase : Dict = os.stat(_UpperCamelCase ).st_size else: __UpperCAmelCase : str = 0 else: __UpperCAmelCase : str = partial(tempfile.NamedTemporaryFile , dir=_UpperCamelCase , delete=_UpperCamelCase ) __UpperCAmelCase : str = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( """%s not found in cache or force_download set to True, downloading to %s""" , _UpperCamelCase , temp_file.name , ) http_get( _UpperCamelCase , _UpperCamelCase , proxies=_UpperCamelCase , resume_size=_UpperCamelCase , user_agent=_UpperCamelCase , ) os.replace(temp_file.name , _UpperCamelCase ) __UpperCAmelCase : str = {"""url""": url, """etag""": etag} __UpperCAmelCase : int = cache_path + """.json""" with open(_UpperCamelCase , """w""" ) as meta_file: json.dump(_UpperCamelCase , _UpperCamelCase ) return cache_path def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : Dict=None ) -> Dict: '''simple docstring''' __UpperCAmelCase : List[Any] = url.encode("""utf-8""" ) __UpperCAmelCase : List[str] = shaaaa(_UpperCamelCase ) __UpperCAmelCase : Tuple = url_hash.hexdigest() if etag: __UpperCAmelCase : List[str] = etag.encode("""utf-8""" ) __UpperCAmelCase : List[Any] = shaaaa(_UpperCamelCase ) filename += "." + etag_hash.hexdigest() if url.endswith(""".h5""" ): filename += ".h5" return filename def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : Tuple=None , _UpperCamelCase : List[Any]=False , _UpperCamelCase : str=None , _UpperCamelCase : str=False , _UpperCamelCase : List[Any]=None , _UpperCamelCase : Tuple=False , _UpperCamelCase : Any=False , _UpperCamelCase : int=False , ) -> Union[str, Any]: '''simple docstring''' if cache_dir is None: __UpperCAmelCase : Dict = TRANSFORMERS_CACHE if isinstance(_UpperCamelCase , _UpperCamelCase ): __UpperCAmelCase : str = str(_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ): __UpperCAmelCase : str = str(_UpperCamelCase ) if is_remote_url(_UpperCamelCase ): # URL, so get it from the cache (downloading if necessary) __UpperCAmelCase : List[Any] = get_from_cache( _UpperCamelCase , cache_dir=_UpperCamelCase , force_download=_UpperCamelCase , proxies=_UpperCamelCase , resume_download=_UpperCamelCase , user_agent=_UpperCamelCase , local_files_only=_UpperCamelCase , ) elif os.path.exists(_UpperCamelCase ): # File, and it exists. __UpperCAmelCase : Union[str, Any] = url_or_filename elif urlparse(_UpperCamelCase ).scheme == "": # File, but it doesn't exist. raise EnvironmentError("""file {} not found""".format(_UpperCamelCase ) ) else: # Something unknown raise ValueError("""unable to parse {} as a URL or as a local path""".format(_UpperCamelCase ) ) if extract_compressed_file: if not is_zipfile(_UpperCamelCase ) and not tarfile.is_tarfile(_UpperCamelCase ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __UpperCAmelCase ,__UpperCAmelCase : Any = os.path.split(_UpperCamelCase ) __UpperCAmelCase : Dict = output_file.replace(""".""" , """-""" ) + """-extracted""" __UpperCAmelCase : str = os.path.join(_UpperCamelCase , _UpperCamelCase ) if os.path.isdir(_UpperCamelCase ) and os.listdir(_UpperCamelCase ) and not force_extract: return output_path_extracted # Prevent parallel extractions __UpperCAmelCase : Optional[int] = output_path + """.lock""" with FileLock(_UpperCamelCase ): shutil.rmtree(_UpperCamelCase , ignore_errors=_UpperCamelCase ) os.makedirs(_UpperCamelCase ) if is_zipfile(_UpperCamelCase ): with ZipFile(_UpperCamelCase , """r""" ) as zip_file: zip_file.extractall(_UpperCamelCase ) zip_file.close() elif tarfile.is_tarfile(_UpperCamelCase ): __UpperCAmelCase : List[Any] = tarfile.open(_UpperCamelCase ) tar_file.extractall(_UpperCamelCase ) tar_file.close() else: raise EnvironmentError("""Archive format of {} could not be identified""".format(_UpperCamelCase ) ) return output_path_extracted return output_path def lowerCamelCase ( _UpperCamelCase : Any , _UpperCamelCase : Optional[Any]="," ) -> Optional[Any]: '''simple docstring''' assert isinstance(_UpperCamelCase , _UpperCamelCase ) if os.path.isfile(_UpperCamelCase ): with open(_UpperCamelCase ) as f: __UpperCAmelCase : Optional[int] = eval(f.read() ) else: __UpperCAmelCase : Tuple = requests.get(_UpperCamelCase ) try: __UpperCAmelCase : Union[str, Any] = requests.json() except Exception: __UpperCAmelCase : Optional[int] = req.content.decode() assert data is not None, "could not connect" try: __UpperCAmelCase : Optional[int] = eval(_UpperCamelCase ) except Exception: __UpperCAmelCase : str = data.split("""\n""" ) req.close() return data def lowerCamelCase ( _UpperCamelCase : List[str] ) -> str: '''simple docstring''' __UpperCAmelCase : Optional[int] = requests.get(_UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = np.array(Image.open(BytesIO(response.content ) ) ) return img def lowerCamelCase ( _UpperCamelCase : str ) -> Dict: '''simple docstring''' __UpperCAmelCase : List[str] = url.split("""/""" )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(_UpperCamelCase ) with open(_UpperCamelCase , """rb""" ) as stream: __UpperCAmelCase : List[Any] = pkl.load(_UpperCamelCase ) __UpperCAmelCase : Any = weights.pop("""model""" ) __UpperCAmelCase : Optional[int] = {} for k, v in model.items(): __UpperCAmelCase : Any = torch.from_numpy(_UpperCamelCase ) if "running_var" in k: __UpperCAmelCase : Optional[int] = torch.tensor([0] ) __UpperCAmelCase : Any = k.replace("""running_var""" , """num_batches_tracked""" ) __UpperCAmelCase : Union[str, Any] = zero return new def lowerCamelCase ( ) -> str: '''simple docstring''' print(f'''{os.path.abspath(os.path.join(_UpperCamelCase , os.pardir ) )}/demo.ipynb''' ) def lowerCamelCase ( _UpperCamelCase : str , _UpperCamelCase : Any="RGB" ) -> Union[str, Any]: '''simple docstring''' assert isinstance(_UpperCamelCase , _UpperCamelCase ) if os.path.isfile(_UpperCamelCase ): __UpperCAmelCase : Tuple = cva.imread(_UpperCamelCase ) else: __UpperCAmelCase : Tuple = get_image_from_url(_UpperCamelCase ) assert img is not None, f'''could not connect to: {im}''' __UpperCAmelCase : List[str] = cva.cvtColor(_UpperCamelCase , cva.COLOR_BGR2RGB ) if input_format == "RGB": __UpperCAmelCase : Union[str, Any] = img[:, :, ::-1] return img def lowerCamelCase ( _UpperCamelCase : Any , _UpperCamelCase : List[str]=1 ) -> Any: '''simple docstring''' return (images[i : i + batch] for i in range(0 , len(_UpperCamelCase ) , _UpperCamelCase ))
139
0
_UpperCAmelCase : List[str] = { "A": ["B", "C", "E"], "B": ["A", "D", "E"], "C": ["A", "F", "G"], "D": ["B"], "E": ["A", "B", "D"], "F": ["C"], "G": ["C"], } def A ( lowercase , lowercase , lowercase ) -> list[str]: '''simple docstring''' UpperCamelCase = set() # keep track of all the paths to be checked UpperCamelCase = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue UpperCamelCase = queue.pop(0 ) # get the last node from the path UpperCamelCase = path[-1] if node not in explored: UpperCamelCase = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: UpperCamelCase = list(lowercase ) new_path.append(lowercase ) queue.append(lowercase ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowercase ) # in case there's no path between the 2 nodes return [] def A ( lowercase , lowercase , lowercase ) -> int: '''simple docstring''' if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 UpperCamelCase = [start] UpperCamelCase = set(lowercase ) # Keep tab on distances from `start` node. UpperCamelCase = {start: 0, target: -1} while queue: UpperCamelCase = queue.pop(0 ) if node == target: UpperCamelCase = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowercase ) queue.append(lowercase ) UpperCamelCase = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, "G", "D")) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, "G", "D")) # returns 4
3
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : Union[str, Any] = { "configuration_git": ["GIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "GitConfig", "GitVisionConfig"], "processing_git": ["GitProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : Dict = [ "GIT_PRETRAINED_MODEL_ARCHIVE_LIST", "GitForCausalLM", "GitModel", "GitPreTrainedModel", "GitVisionModel", ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _UpperCAmelCase : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
3
1
'''simple docstring''' def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : list[list[int]] , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : set ): '''simple docstring''' A , A: Any = len(lowerCamelCase__ ), len(grid[0] ) if ( min(lowerCamelCase__ , lowerCamelCase__ ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) A: int = 0 count += depth_first_search(lowerCamelCase__ , row + 1 , lowerCamelCase__ , lowerCamelCase__ ) count += depth_first_search(lowerCamelCase__ , row - 1 , lowerCamelCase__ , lowerCamelCase__ ) count += depth_first_search(lowerCamelCase__ , lowerCamelCase__ , col + 1 , lowerCamelCase__ ) count += depth_first_search(lowerCamelCase__ , lowerCamelCase__ , col - 1 , lowerCamelCase__ ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
135
'''simple docstring''' from __future__ import annotations def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : list[int] , lowerCamelCase__ : list[int] , lowerCamelCase__ : list[int] , lowerCamelCase__ : list[list[str]] , lowerCamelCase__ : int , ): '''simple docstring''' A: Union[str, Any] = len(lowerCamelCase__ ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append([""". """ * i + """Q """ + """. """ * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(lowerCamelCase__ ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , lowerCamelCase__ , lowerCamelCase__ , ) def _SCREAMING_SNAKE_CASE ( lowerCamelCase__ : int ): '''simple docstring''' A: list[list[str]] = [] depth_first_search([] , [] , [] , lowerCamelCase__ , lowerCamelCase__ ) # Print all the boards for board in boards: for column in board: print(lowerCamelCase__ ) print("""""" ) print(len(lowerCamelCase__ ) , """solutions were found.""" ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
135
1
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging UpperCAmelCase__ : Optional[Any] = logging.get_logger(__name__) class __lowercase ( lowerCamelCase__ ): __UpperCAmelCase = ['''pixel_values'''] def __init__( self , lowercase_ = True , lowercase_ = 1 / 2_5_5 , lowercase_ = True , lowercase_ = 8 , **lowercase_ , ) -> None: super().__init__(**lowercase_) __snake_case = do_rescale __snake_case = rescale_factor __snake_case = do_pad __snake_case = pad_size def _a ( self , lowercase_ , lowercase_ , lowercase_ = None , **lowercase_) -> np.ndarray: return rescale(lowercase_ , scale=lowercase_ , data_format=lowercase_ , **lowercase_) def _a ( self , lowercase_ , lowercase_ , lowercase_ = None) -> List[str]: __snake_case , __snake_case = get_image_size(lowercase_) __snake_case = (old_height // size + 1) * size - old_height __snake_case = (old_width // size + 1) * size - old_width return pad(lowercase_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=lowercase_) def _a ( self , lowercase_ , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = None , lowercase_ = ChannelDimension.FIRST , **lowercase_ , ) -> int: __snake_case = do_rescale if do_rescale is not None else self.do_rescale __snake_case = rescale_factor if rescale_factor is not None else self.rescale_factor __snake_case = do_pad if do_pad is not None else self.do_pad __snake_case = pad_size if pad_size is not None else self.pad_size __snake_case = make_list_of_images(lowercase_) if not valid_images(lowercase_): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. __snake_case = [to_numpy_array(lowercase_) for image in images] if do_rescale: __snake_case = [self.rescale(image=lowercase_ , scale=lowercase_) for image in images] if do_pad: __snake_case = [self.pad(lowercase_ , size=lowercase_) for image in images] __snake_case = [to_channel_dimension_format(lowercase_ , lowercase_) for image in images] __snake_case = {'pixel_values': images} return BatchFeature(data=lowercase_ , tensor_type=lowercase_)
676
def A ( snake_case__ : int ) -> bool: '''simple docstring''' if not isinstance(snake_case__ , snake_case__ ): __snake_case = f"Input value of [number={number}] must be an integer" raise TypeError(snake_case__ ) if number < 0: return False __snake_case = number * number while number > 0: if number % 10 != number_square % 10: return False number //= 10 number_square //= 10 return True if __name__ == "__main__": import doctest doctest.testmod()
676
1
'''simple docstring''' def _A ( A ) -> str: if number > 0: raise ValueError("input must be a negative integer" ) lowercase : int = len(bin(A )[3:] ) lowercase : Tuple = bin(abs(A ) - (1 << binary_number_length) )[3:] lowercase : Optional[int] = ( ( "1" + "0" * (binary_number_length - len(A )) + twos_complement_number ) if number < 0 else "0" ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
372
'''simple docstring''' 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, ) lowerCAmelCase : List[Any] = { """configuration_albert""": ["""ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """AlbertConfig""", """AlbertOnnxConfig"""], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Any = ["""AlbertTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Optional[Any] = ["""AlbertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : List[str] = [ """ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """AlbertForMaskedLM""", """AlbertForMultipleChoice""", """AlbertForPreTraining""", """AlbertForQuestionAnswering""", """AlbertForSequenceClassification""", """AlbertForTokenClassification""", """AlbertModel""", """AlbertPreTrainedModel""", """load_tf_weights_in_albert""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Tuple = [ """TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFAlbertForMaskedLM""", """TFAlbertForMultipleChoice""", """TFAlbertForPreTraining""", """TFAlbertForQuestionAnswering""", """TFAlbertForSequenceClassification""", """TFAlbertForTokenClassification""", """TFAlbertMainLayer""", """TFAlbertModel""", """TFAlbertPreTrainedModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Optional[int] = [ """FlaxAlbertForMaskedLM""", """FlaxAlbertForMultipleChoice""", """FlaxAlbertForPreTraining""", """FlaxAlbertForQuestionAnswering""", """FlaxAlbertForSequenceClassification""", """FlaxAlbertForTokenClassification""", """FlaxAlbertModel""", """FlaxAlbertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys lowerCAmelCase : Union[str, Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
372
1
def __lowercase ( _SCREAMING_SNAKE_CASE = 10_00 ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = 3 SCREAMING_SNAKE_CASE = 0 while a < n: if a % 3 == 0 or a % 5 == 0: result += a elif a % 15 == 0: result -= a a += 1 return result if __name__ == "__main__": print(F'''{solution() = }''')
116
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__) class UpperCamelCase__ ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : int ,*lowerCamelCase__ : int ,**lowerCamelCase__ : List[Any] ) -> None: '''simple docstring''' warnings.warn( """The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.""" """ Please use DeformableDetrImageProcessor instead.""" ,lowerCamelCase__ ,) super().__init__(*lowerCamelCase__ ,**lowerCamelCase__ )
116
1
"""simple docstring""" import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def lowercase ( lowerCAmelCase__ ): def wrapper(*lowerCAmelCase__ ,**lowerCAmelCase__ ): lowerCamelCase_ = timeit.default_timer() lowerCamelCase_ = func(*lowerCAmelCase__ ,**lowerCAmelCase__ ) lowerCamelCase_ = timeit.default_timer() - starttime return delta lowerCamelCase_ = func.__name__ return wrapper def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__=100 ,lowerCAmelCase__=None ): lowerCamelCase_ = [] lowerCamelCase_ = seq_shapes or {} for i in range(lowerCAmelCase__ ): lowerCamelCase_ = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(lowerCAmelCase__ ,_ArrayXD ): lowerCamelCase_ = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(lowerCAmelCase__ ,datasets.Value ): if v.dtype == "string": lowerCamelCase_ = '''The small grey turtle was surprisingly fast when challenged.''' else: lowerCamelCase_ = np.random.randint(10 ,size=1 ).astype(v.dtype ).item() elif isinstance(lowerCAmelCase__ ,datasets.Sequence ): while isinstance(lowerCAmelCase__ ,datasets.Sequence ): lowerCamelCase_ = v.feature lowerCamelCase_ = seq_shapes[k] lowerCamelCase_ = np.random.rand(*lowerCAmelCase__ ).astype(v.dtype ) lowerCamelCase_ = data dummy_data.append((i, example) ) return dummy_data def lowercase ( lowerCAmelCase__ ,lowerCAmelCase__ ,lowerCAmelCase__=100 ,lowerCAmelCase__=None ): lowerCamelCase_ = generate_examples(lowerCAmelCase__ ,num_examples=lowerCAmelCase__ ,seq_shapes=lowerCAmelCase__ ) with ArrowWriter(features=lowerCAmelCase__ ,path=lowerCAmelCase__ ) as writer: for key, record in dummy_data: lowerCamelCase_ = features.encode_example(lowerCAmelCase__ ) writer.write(lowerCAmelCase__ ) lowerCamelCase_ , lowerCamelCase_ = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f"Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}." ) lowerCamelCase_ = datasets.Dataset.from_file(filename=lowerCAmelCase__ ,info=datasets.DatasetInfo(features=lowerCAmelCase__ ) ) return dataset
29
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""", """NllbMoeForConditionalGeneration""", """NllbMoeModel""", """NllbMoePreTrainedModel""", """NllbMoeTop2Router""", """NllbMoeSparseMLP""", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
651
0
"""simple docstring""" import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Audio, ClassLabel, Features from .base import TaskTemplate @dataclass(frozen=UpperCAmelCase_ ) class lowerCAmelCase__ ( UpperCAmelCase_ ): lowercase__ : str = field(default="""audio-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) lowercase__ : ClassVar[Features] = Features({"""audio""": Audio()} ) lowercase__ : ClassVar[Features] = Features({"""labels""": ClassLabel} ) lowercase__ : str = "audio" lowercase__ : str = "labels" def lowercase_ ( self , UpperCamelCase__ ): '''simple docstring''' if self.label_column not in features: raise ValueError(f"""Column {self.label_column} is not present in features.""" ) if not isinstance(features[self.label_column] , UpperCamelCase__ ): raise ValueError(f"""Column {self.label_column} is not a ClassLabel.""" ) A__ = copy.deepcopy(self ) A__ = self.label_schema.copy() A__ = features[self.label_column] A__ = label_schema return task_template @property def lowercase_ ( self ): '''simple docstring''' return { self.audio_column: "audio", self.label_column: "labels", }
261
"""simple docstring""" def __a ( A = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' A__ = set() # Replace all the whitespace in our sentence A__ = input_str.replace(" " , "" ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(A ) == 26 def __a ( A = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' A__ = [False] * 26 for char in input_str: if char.islower(): A__ = True elif char.isupper(): A__ = True return all(A ) def __a ( A = "The quick brown fox jumps over the lazy dog" , ) -> bool: '''simple docstring''' return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def __a ( ) -> None: '''simple docstring''' from timeit import timeit A__ = "from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest" print(timeit("is_pangram()" , setup=A ) ) print(timeit("is_pangram_faster()" , setup=A ) ) print(timeit("is_pangram_fastest()" , setup=A ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
261
1
"""simple docstring""" import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging snake_case : List[Any] = logging.get_logger(__name__) def A ( __snake_case: List[Any] , __snake_case: str ) -> List[str]: """simple docstring""" __magic_name__ = nn.functional.normalize(__snake_case ) __magic_name__ = nn.functional.normalize(__snake_case ) return torch.mm(__snake_case , normalized_text_embeds.t() ) class UpperCamelCase__ ( a_): """simple docstring""" __UpperCAmelCase = CLIPConfig __UpperCAmelCase = ["""CLIPEncoderLayer"""] def __init__( self : Union[str, Any] , UpperCamelCase_ : CLIPConfig ): '''simple docstring''' super().__init__(UpperCamelCase_ ) __magic_name__ = CLIPVisionModel(config.vision_config ) __magic_name__ = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=UpperCamelCase_ ) __magic_name__ = nn.Parameter(torch.ones(1_7 , config.projection_dim ) , requires_grad=UpperCamelCase_ ) __magic_name__ = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=UpperCamelCase_ ) __magic_name__ = nn.Parameter(torch.ones(1_7 ) , requires_grad=UpperCamelCase_ ) __magic_name__ = nn.Parameter(torch.ones(3 ) , requires_grad=UpperCamelCase_ ) @torch.no_grad() def a__ ( self : int , UpperCamelCase_ : int , UpperCamelCase_ : List[str] ): '''simple docstring''' __magic_name__ = self.vision_model(UpperCamelCase_ )[1] # pooled_output __magic_name__ = self.visual_projection(UpperCamelCase_ ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 __magic_name__ = cosine_distance(UpperCamelCase_ , self.special_care_embeds ).cpu().float().numpy() __magic_name__ = cosine_distance(UpperCamelCase_ , self.concept_embeds ).cpu().float().numpy() __magic_name__ = [] __magic_name__ = image_embeds.shape[0] for i in range(UpperCamelCase_ ): __magic_name__ = {'special_scores': {}, 'special_care': [], 'concept_scores': {}, 'bad_concepts': []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images __magic_name__ = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): __magic_name__ = special_cos_dist[i][concept_idx] __magic_name__ = self.special_care_embeds_weights[concept_idx].item() __magic_name__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img['special_scores'][concept_idx]} ) __magic_name__ = 0.01 for concept_idx in range(len(cos_dist[0] ) ): __magic_name__ = cos_dist[i][concept_idx] __magic_name__ = self.concept_embeds_weights[concept_idx].item() __magic_name__ = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(UpperCamelCase_ ) result.append(UpperCamelCase_ ) __magic_name__ = [len(res['bad_concepts'] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def a__ ( self : List[Any] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : torch.FloatTensor ): '''simple docstring''' __magic_name__ = self.vision_model(UpperCamelCase_ )[1] # pooled_output __magic_name__ = self.visual_projection(UpperCamelCase_ ) __magic_name__ = cosine_distance(UpperCamelCase_ , self.special_care_embeds ) __magic_name__ = cosine_distance(UpperCamelCase_ , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images __magic_name__ = 0.0 __magic_name__ = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) __magic_name__ = torch.any(special_scores > 0 , dim=1 ) __magic_name__ = special_care * 0.01 __magic_name__ = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) __magic_name__ = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) __magic_name__ = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
545
"""simple docstring""" def A ( __snake_case: int ) -> int: """simple docstring""" if divisor % 5 == 0 or divisor % 2 == 0: return 0 __magic_name__ = 1 __magic_name__ = 1 while repunit: __magic_name__ = (1_0 * repunit + 1) % divisor repunit_index += 1 return repunit_index def A ( __snake_case: int = 1_0_0_0_0_0_0 ) -> int: """simple docstring""" __magic_name__ = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(__snake_case ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(f"""{solution() = }""")
545
1
import argparse import json import os from collections import OrderedDict import torch from transformers import LukeConfig, LukeForMaskedLM, MLukeTokenizer, XLMRobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> Dict: # Load configuration defined in the metadata file with open(lowerCAmelCase__ ) as metadata_file: UpperCamelCase_ = json.load(lowerCAmelCase__ ) UpperCamelCase_ = LukeConfig(use_entity_aware_attention=lowerCAmelCase__ , **metadata["model_config"] ) # Load in the weights from the checkpoint_path UpperCamelCase_ = torch.load(lowerCAmelCase__ , map_location="cpu" )["module"] # Load the entity vocab file UpperCamelCase_ = load_original_entity_vocab(lowerCAmelCase__ ) # add an entry for [MASK2] UpperCamelCase_ = max(entity_vocab.values() ) + 1 config.entity_vocab_size += 1 UpperCamelCase_ = XLMRobertaTokenizer.from_pretrained(metadata["model_config"]["bert_model_name"] ) # Add special tokens to the token vocabulary for downstream tasks UpperCamelCase_ = AddedToken("<ent>" , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) UpperCamelCase_ = AddedToken("<ent2>" , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) tokenizer.add_special_tokens({"additional_special_tokens": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(F'''Saving tokenizer to {pytorch_dump_folder_path}''' ) tokenizer.save_pretrained(lowerCAmelCase__ ) with open(os.path.join(lowerCAmelCase__ , "tokenizer_config.json" ) , "r" ) as f: UpperCamelCase_ = json.load(lowerCAmelCase__ ) UpperCamelCase_ = "MLukeTokenizer" with open(os.path.join(lowerCAmelCase__ , "tokenizer_config.json" ) , "w" ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) with open(os.path.join(lowerCAmelCase__ , MLukeTokenizer.vocab_files_names["entity_vocab_file"] ) , "w" ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) UpperCamelCase_ = MLukeTokenizer.from_pretrained(lowerCAmelCase__ ) # Initialize the embeddings of the special tokens UpperCamelCase_ = tokenizer.convert_tokens_to_ids(["@"] )[0] UpperCamelCase_ = tokenizer.convert_tokens_to_ids(["#"] )[0] UpperCamelCase_ = state_dict["embeddings.word_embeddings.weight"] UpperCamelCase_ = word_emb[ent_init_index].unsqueeze(0 ) UpperCamelCase_ = word_emb[enta_init_index].unsqueeze(0 ) UpperCamelCase_ = torch.cat([word_emb, ent_emb, enta_emb] ) # add special tokens for 'entity_predictions.bias' for bias_name in ["lm_head.decoder.bias", "lm_head.bias"]: UpperCamelCase_ = state_dict[bias_name] UpperCamelCase_ = decoder_bias[ent_init_index].unsqueeze(0 ) UpperCamelCase_ = decoder_bias[enta_init_index].unsqueeze(0 ) UpperCamelCase_ = torch.cat([decoder_bias, ent_decoder_bias, enta_decoder_bias] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: UpperCamelCase_ = F'''encoder.layer.{layer_index}.attention.self.''' UpperCamelCase_ = state_dict[prefix + matrix_name] UpperCamelCase_ = state_dict[prefix + matrix_name] UpperCamelCase_ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks UpperCamelCase_ = state_dict["entity_embeddings.entity_embeddings.weight"] UpperCamelCase_ = entity_emb[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase_ = torch.cat([entity_emb, entity_mask_emb] ) # add [MASK2] for 'entity_predictions.bias' UpperCamelCase_ = state_dict["entity_predictions.bias"] UpperCamelCase_ = entity_prediction_bias[entity_vocab["[MASK]"]].unsqueeze(0 ) UpperCamelCase_ = torch.cat([entity_prediction_bias, entity_mask_bias] ) UpperCamelCase_ = LukeForMaskedLM(config=lowerCAmelCase__ ).eval() state_dict.pop("entity_predictions.decoder.weight" ) state_dict.pop("lm_head.decoder.weight" ) state_dict.pop("lm_head.decoder.bias" ) UpperCamelCase_ = OrderedDict() for key, value in state_dict.items(): if not (key.startswith("lm_head" ) or key.startswith("entity_predictions" )): UpperCamelCase_ = state_dict[key] else: UpperCamelCase_ = state_dict[key] UpperCamelCase_ , UpperCamelCase_ = model.load_state_dict(lowerCAmelCase__ , strict=lowerCAmelCase__ ) if set(lowerCAmelCase__ ) != {"luke.embeddings.position_ids"}: raise ValueError(F'''Unexpected unexpected_keys: {unexpected_keys}''' ) if set(lowerCAmelCase__ ) != { "lm_head.decoder.weight", "lm_head.decoder.bias", "entity_predictions.decoder.weight", }: raise ValueError(F'''Unexpected missing_keys: {missing_keys}''' ) model.tie_weights() assert (model.luke.embeddings.word_embeddings.weight == model.lm_head.decoder.weight).all() assert (model.luke.entity_embeddings.entity_embeddings.weight == model.entity_predictions.decoder.weight).all() # Check outputs UpperCamelCase_ = MLukeTokenizer.from_pretrained(lowerCAmelCase__ , task="entity_classification" ) UpperCamelCase_ = "ISO 639-3 uses the code fas for the dialects spoken across Iran and アフガニスタン (Afghanistan)." UpperCamelCase_ = (0, 9) UpperCamelCase_ = tokenizer(lowerCAmelCase__ , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase_ = model(**lowerCAmelCase__ ) # Verify word hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_ = torch.Size((1, 33, 768) ) UpperCamelCase_ = torch.tensor([[0.08_92, 0.05_96, -0.28_19], [0.01_34, 0.11_99, 0.05_73], [-0.01_69, 0.09_27, 0.06_44]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}''' ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCAmelCase__ , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": raise NotImplementedError else: # base UpperCamelCase_ = torch.Size((1, 1, 768) ) UpperCamelCase_ = torch.tensor([[-0.14_82, 0.06_09, 0.03_22]] ) if not (outputs.entity_last_hidden_state.shape == expected_shape): raise ValueError( F'''Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is''' F''' {expected_shape}''' ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , lowerCAmelCase__ , atol=1e-4 ): raise ValueError # Verify masked word/entity prediction UpperCamelCase_ = MLukeTokenizer.from_pretrained(lowerCAmelCase__ ) UpperCamelCase_ = "Tokyo is the capital of <mask>." UpperCamelCase_ = (24, 30) UpperCamelCase_ = tokenizer(lowerCAmelCase__ , entity_spans=[span] , return_tensors="pt" ) UpperCamelCase_ = model(**lowerCAmelCase__ ) UpperCamelCase_ = encoding["input_ids"][0].tolist() UpperCamelCase_ = input_ids.index(tokenizer.convert_tokens_to_ids("<mask>" ) ) UpperCamelCase_ = outputs.logits[0][mask_position_id].argmax(dim=-1 ) assert "Japan" == tokenizer.decode(lowerCAmelCase__ ) UpperCamelCase_ = outputs.entity_logits[0][0].argmax().item() UpperCamelCase_ = [ entity for entity, entity_id in tokenizer.entity_vocab.items() if entity_id == predicted_entity_id ] assert [e for e in multilingual_predicted_entities if e.startswith("en:" )][0] == "en:Japan" # Finally, save our PyTorch model and tokenizer print("Saving PyTorch model to {}".format(lowerCAmelCase__ ) ) model.save_pretrained(lowerCAmelCase__ ) def lowerCAmelCase_ ( UpperCamelCase_ ) -> Union[str, Any]: UpperCamelCase_ = ["[MASK]", "[PAD]", "[UNK]"] UpperCamelCase_ = [json.loads(lowerCAmelCase__ ) for line in open(lowerCAmelCase__ )] UpperCamelCase_ = {} for entry in data: UpperCamelCase_ = entry["id"] for entity_name, language in entry["entities"]: if entity_name in SPECIAL_TOKENS: UpperCamelCase_ = entity_id break UpperCamelCase_ = F'''{language}:{entity_name}''' UpperCamelCase_ = entity_id return new_mapping if __name__ == "__main__": _UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.') parser.add_argument( '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.' ) parser.add_argument( '--entity_vocab_path', default=None, type=str, help='Path to an entity_vocab.tsv file, containing the entity vocabulary.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.' ) parser.add_argument( '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.' ) _UpperCAmelCase = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
714
# Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=0 ) -> int: # Format the message. if name is None: UpperCamelCase_ = None else: UpperCamelCase_ = "." * max(0 , spaces - 2 ) + "# {:" + str(50 - spaces ) + "s}" UpperCamelCase_ = fmt.format(UpperCamelCase_ ) # Print and recurse (if needed). if isinstance(UpperCamelCase_ , UpperCamelCase_ ): if msg is not None: print(UpperCamelCase_ ) for k in val.keys(): recursive_print(UpperCamelCase_ , val[k] , spaces + 2 ) elif isinstance(UpperCamelCase_ , torch.Tensor ): print(UpperCamelCase_ , ":" , val.size() ) else: print(UpperCamelCase_ , ":" , UpperCamelCase_ ) def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. UpperCamelCase_ = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] UpperCamelCase_ = (num_heads, hidden_size, num_splits) + input_shape[1:] UpperCamelCase_ = param.view(*UpperCamelCase_ ) UpperCamelCase_ = param.transpose(0 , 2 ) UpperCamelCase_ = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] UpperCamelCase_ = (num_heads, num_splits, hidden_size) + input_shape[1:] UpperCamelCase_ = param.view(*UpperCamelCase_ ) UpperCamelCase_ = param.transpose(0 , 1 ).contiguous() UpperCamelCase_ = param.view(*UpperCamelCase_ ) return param def lowerCAmelCase_ ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) -> int: # The converted output model. UpperCamelCase_ = {} # old versions did not store training args UpperCamelCase_ = input_state_dict.get("args" , UpperCamelCase_ ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) UpperCamelCase_ = ds_args.padded_vocab_size UpperCamelCase_ = ds_args.max_position_embeddings UpperCamelCase_ = ds_args.hidden_size UpperCamelCase_ = ds_args.num_layers UpperCamelCase_ = ds_args.num_attention_heads UpperCamelCase_ = ds_args.ffn_hidden_size # pprint(config) # The number of heads. UpperCamelCase_ = config.n_head # The hidden_size per head. UpperCamelCase_ = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): UpperCamelCase_ = input_state_dict["checkpoint_version"] else: UpperCamelCase_ = 0.0 # The model. UpperCamelCase_ = input_state_dict["model"] # The language model. UpperCamelCase_ = model["language_model"] # The embeddings. UpperCamelCase_ = lm["embedding"] # The word embeddings. UpperCamelCase_ = embeddings["word_embeddings"]["weight"] # Truncate the embedding table to vocab_size rows. UpperCamelCase_ = word_embeddings[: config.vocab_size, :] UpperCamelCase_ = word_embeddings # The position embeddings. UpperCamelCase_ = embeddings["position_embeddings"]["weight"] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] UpperCamelCase_ = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( F'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. UpperCamelCase_ = pos_embeddings # The transformer. UpperCamelCase_ = lm["transformer"] if "transformer" in lm.keys() else lm["encoder"] # The regex to extract layer names. UpperCamelCase_ = re.compile(r"layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)" ) # The simple map of names for "automated" rules. UpperCamelCase_ = { "attention.dense": ".attn.c_proj.", "self_attention.dense": ".attn.c_proj.", "mlp.dense_h_to_4h": ".mlp.c_fc.", "mlp.dense_4h_to_h": ".mlp.c_proj.", } # Extract the layers. for key, val in transformer.items(): # Match the name. UpperCamelCase_ = layer_re.match(UpperCamelCase_ ) # Stop if that's not a layer if m is None: break # The index of the layer. UpperCamelCase_ = int(m.group(1 ) ) # The name of the operation. UpperCamelCase_ = m.group(2 ) # Is it a weight or a bias? UpperCamelCase_ = m.group(3 ) # The name of the layer. UpperCamelCase_ = F'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith("layernorm" ): UpperCamelCase_ = "ln_1" if op_name.startswith("input" ) else "ln_2" UpperCamelCase_ = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. UpperCamelCase_ = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , UpperCamelCase_ , UpperCamelCase_ ) UpperCamelCase_ = causal_mask # Insert a "dummy" tensor for masked_bias. UpperCamelCase_ = torch.tensor(-1e4 , dtype=torch.floataa ) UpperCamelCase_ = masked_bias UpperCamelCase_ = fix_query_key_value_ordering(UpperCamelCase_ , UpperCamelCase_ , 3 , UpperCamelCase_ , UpperCamelCase_ ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. UpperCamelCase_ = out_val.transpose(0 , 1 ).contiguous() # Store. UpperCamelCase_ = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": UpperCamelCase_ = fix_query_key_value_ordering(UpperCamelCase_ , UpperCamelCase_ , 3 , UpperCamelCase_ , UpperCamelCase_ ) # Store. No change of shape. UpperCamelCase_ = out_val # Transpose the weights. elif weight_or_bias == "weight": UpperCamelCase_ = megatron_to_transformers[op_name] UpperCamelCase_ = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": UpperCamelCase_ = megatron_to_transformers[op_name] UpperCamelCase_ = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. UpperCamelCase_ = transformer["final_layernorm.weight"] UpperCamelCase_ = transformer["final_layernorm.bias"] # For LM head, transformers' wants the matrix to weight embeddings. UpperCamelCase_ = word_embeddings # It should be done! return output_state_dict def lowerCAmelCase_ ( ) -> Union[str, Any]: # Create the argument parser. UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument("--print-checkpoint-structure" , action="store_true" ) parser.add_argument( "path_to_checkpoint" , type=UpperCamelCase_ , help="Path to the checkpoint file (.zip archive or direct .pt file)" , ) parser.add_argument( "--config_file" , default="" , type=UpperCamelCase_ , help="An optional config json file describing the pre-trained model." , ) UpperCamelCase_ = parser.parse_args() # Extract the basename. UpperCamelCase_ = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(F'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith(".zip" ): with zipfile.ZipFile(args.path_to_checkpoint , "r" ) as checkpoint: with checkpoint.open("release/mp_rank_00/model_optim_rng.pt" ) as pytorch_dict: UpperCamelCase_ = torch.load(UpperCamelCase_ , map_location="cpu" ) else: UpperCamelCase_ = torch.load(args.path_to_checkpoint , map_location="cpu" ) UpperCamelCase_ = input_state_dict.get("args" , UpperCamelCase_ ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: UpperCamelCase_ = "gelu_fast" elif ds_args.openai_gelu: UpperCamelCase_ = "gelu_new" else: UpperCamelCase_ = "gelu" else: # in the very early days this used to be "gelu_new" UpperCamelCase_ = "gelu_new" # Spell out all parameters in case the defaults change. UpperCamelCase_ = GPTaConfig( vocab_size=50257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=UpperCamelCase_ , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1e-5 , initializer_range=0.02 , summary_type="cls_index" , summary_use_proj=UpperCamelCase_ , summary_activation=UpperCamelCase_ , summary_proj_to_labels=UpperCamelCase_ , summary_first_dropout=0.1 , scale_attn_weights=UpperCamelCase_ , use_cache=UpperCamelCase_ , bos_token_id=50256 , eos_token_id=50256 , ) else: UpperCamelCase_ = GPTaConfig.from_json_file(args.config_file ) UpperCamelCase_ = ["GPT2LMHeadModel"] # Convert. print("Converting" ) UpperCamelCase_ = convert_megatron_checkpoint(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(UpperCamelCase_ , UpperCamelCase_ ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: UpperCamelCase_ = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": UpperCamelCase_ = "gpt2" elif tokenizer_type == "PretrainedFromHF": UpperCamelCase_ = ds_args.tokenizer_name_or_path else: raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: UpperCamelCase_ = "gpt2" UpperCamelCase_ = AutoTokenizer.from_pretrained(UpperCamelCase_ ) UpperCamelCase_ = type(UpperCamelCase_ ).__name__ UpperCamelCase_ = tokenizer_class # Store the config to file. print("Saving config" ) config.save_pretrained(UpperCamelCase_ ) # Save tokenizer based on args print(F'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(UpperCamelCase_ ) # Store the state_dict to file. UpperCamelCase_ = os.path.join(UpperCamelCase_ , "pytorch_model.bin" ) print(F'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(UpperCamelCase_ , UpperCamelCase_ ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
371
0
import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _SCREAMING_SNAKE_CASE ( a ) -> Tuple: random.seed(a ) np.random.seed(a ) torch.manual_seed(a ) torch.cuda.manual_seed_all(a ) # ^^ safe to call this function even if cuda is not available class _A: """simple docstring""" def __init__( self , _A , _A = 0.9_9_9_9 , _A = 0.0 , _A = 0 , _A = False , _A = 1.0 , _A = 2 / 3 , _A = None , _A = None , **_A , ): if isinstance(_A , torch.nn.Module ): __A : Optional[Any] = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage`' , '1.0.0' , _A , standard_warn=_A , ) __A : Optional[Any] = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility __A : Optional[Any] = True if kwargs.get('max_value' , _A ) is not None: __A : Optional[int] = 'The `max_value` argument is deprecated. Please use `decay` instead.' deprecate('max_value' , '1.0.0' , _A , standard_warn=_A ) __A : Optional[int] = kwargs['max_value'] if kwargs.get('min_value' , _A ) is not None: __A : List[Any] = 'The `min_value` argument is deprecated. Please use `min_decay` instead.' deprecate('min_value' , '1.0.0' , _A , standard_warn=_A ) __A : Dict = kwargs['min_value'] __A : int = list(_A ) __A : int = [p.clone().detach() for p in parameters] if kwargs.get('device' , _A ) is not None: __A : Dict = 'The `device` argument is deprecated. Please use `to` instead.' deprecate('device' , '1.0.0' , _A , standard_warn=_A ) self.to(device=kwargs['device'] ) __A : Any = None __A : Tuple = decay __A : str = min_decay __A : Any = update_after_step __A : Optional[int] = use_ema_warmup __A : Optional[Any] = inv_gamma __A : List[Any] = power __A : Dict = 0 __A : Union[str, Any] = None # set in `step()` __A : Tuple = model_cls __A : Optional[int] = model_config @classmethod def UpperCAmelCase_ ( cls , _A , _A ): __A , __A : Optional[int] = model_cls.load_config(_A , return_unused_kwargs=_A ) __A : List[str] = model_cls.from_pretrained(_A ) __A : str = cls(model.parameters() , model_cls=_A , model_config=model.config ) ema_model.load_state_dict(_A ) return ema_model def UpperCAmelCase_ ( self , _A ): if self.model_cls is None: raise ValueError('`save_pretrained` can only be used if `model_cls` was defined at __init__.' ) if self.model_config is None: raise ValueError('`save_pretrained` can only be used if `model_config` was defined at __init__.' ) __A : Tuple = self.model_cls.from_config(self.model_config ) __A : Optional[int] = self.state_dict() state_dict.pop('shadow_params' , _A ) model.register_to_config(**_A ) self.copy_to(model.parameters() ) model.save_pretrained(_A ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: __A : List[str] = 1 - (1 + step / self.inv_gamma) ** -self.power else: __A : Dict = (1 + step) / (10 + step) __A : Optional[Any] = min(_A , self.decay ) # make sure decay is not smaller than min_decay __A : Union[str, Any] = max(_A , self.min_decay ) return cur_decay_value @torch.no_grad() def UpperCAmelCase_ ( self , _A ): if isinstance(_A , torch.nn.Module ): __A : Union[str, Any] = ( 'Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ' 'Please pass the parameters of the module instead.' ) deprecate( 'passing a `torch.nn.Module` to `ExponentialMovingAverage.step`' , '1.0.0' , _A , standard_warn=_A , ) __A : Union[str, Any] = parameters.parameters() __A : Dict = list(_A ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. __A : Optional[Any] = self.get_decay(self.optimization_step ) __A : Union[str, Any] = decay __A : List[Any] = 1 - decay __A : int = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , _A ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): __A : Tuple = deepspeed.zero.GatheredParameters(_A , modifier_rank=_A ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(_A ) def UpperCAmelCase_ ( self , _A ): __A : List[Any] = list(_A ) for s_param, param in zip(self.shadow_params , _A ): param.data.copy_(s_param.to(param.device ).data ) def UpperCAmelCase_ ( self , _A=None , _A=None ): __A : Optional[int] = [ p.to(device=_A , dtype=_A ) if p.is_floating_point() else p.to(device=_A ) for p in self.shadow_params ] def UpperCAmelCase_ ( self ): return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def UpperCAmelCase_ ( self , _A ): __A : int = [param.detach().cpu().clone() for param in parameters] def UpperCAmelCase_ ( self , _A ): if self.temp_stored_params is None: raise RuntimeError('This ExponentialMovingAverage has no `store()`ed weights ' 'to `restore()`' ) for c_param, param in zip(self.temp_stored_params , _A ): param.data.copy_(c_param.data ) # Better memory-wise. __A : Union[str, Any] = None def UpperCAmelCase_ ( self , _A ): __A : Any = copy.deepcopy(_A ) __A : Dict = state_dict.get('decay' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('Decay must be between 0 and 1' ) __A : Union[str, Any] = state_dict.get('min_decay' , self.min_decay ) if not isinstance(self.min_decay , _A ): raise ValueError('Invalid min_decay' ) __A : Union[str, Any] = state_dict.get('optimization_step' , self.optimization_step ) if not isinstance(self.optimization_step , _A ): raise ValueError('Invalid optimization_step' ) __A : str = state_dict.get('update_after_step' , self.update_after_step ) if not isinstance(self.update_after_step , _A ): raise ValueError('Invalid update_after_step' ) __A : Union[str, Any] = state_dict.get('use_ema_warmup' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , _A ): raise ValueError('Invalid use_ema_warmup' ) __A : int = state_dict.get('inv_gamma' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('Invalid inv_gamma' ) __A : int = state_dict.get('power' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('Invalid power' ) __A : Tuple = state_dict.get('shadow_params' , _A ) if shadow_params is not None: __A : str = shadow_params if not isinstance(self.shadow_params , _A ): raise ValueError('shadow_params must be a list' ) if not all(isinstance(_A , torch.Tensor ) for p in self.shadow_params ): raise ValueError('shadow_params must all be Tensors' )
239
from __future__ import annotations import string from itertools import cycle, product from pathlib import Path UpperCAmelCase : str = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) UpperCAmelCase : list[int] = [ord(letter) for letter in string.ascii_lowercase] UpperCAmelCase : set[int] = {ord(char) for char in VALID_CHARS} UpperCAmelCase : list[str] = ["the", "be", "to", "of", "and", "in", "that", "have"] def _SCREAMING_SNAKE_CASE ( a , a ) -> str | None: __A : str = "" __A : int __A : int __A : int for keychar, cipherchar in zip(cycle(a ) , a ): __A : List[Any] = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(a ) return decoded def _SCREAMING_SNAKE_CASE ( a ) -> list[str]: __A : list[str] = [] for key in product(a , repeat=3 ): __A : str = try_key(a , a ) if encoded is not None: possibles.append(a ) return possibles def _SCREAMING_SNAKE_CASE ( a , a ) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()] def _SCREAMING_SNAKE_CASE ( a = "p059_cipher.txt" ) -> int: __A : list[int] __A : list[str] __A : str __A : str __A : str = Path(a ).parent.joinpath(a ).read_text(encoding='utf-8' ) __A : Union[str, Any] = [int(a ) for number in data.strip().split(',' )] __A : Any = filter_valid_chars(a ) for common_word in COMMON_WORDS: __A : Tuple = filter_common_word(a , a ) if len(a ) == 1: break __A : Union[str, Any] = possibles[0] return sum(ord(a ) for char in decoded_text ) if __name__ == "__main__": print(F"""{solution() = }""")
239
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCAmelCase__ = { "configuration_owlvit": [ "OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig", ], "processing_owlvit": ["OwlViTProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = ["OwlViTFeatureExtractor"] lowerCAmelCase__ = ["OwlViTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase__ = [ "OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "OwlViTModel", "OwlViTPreTrainedModel", "OwlViTTextModel", "OwlViTVisionModel", "OwlViTForObjectDetection", ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys lowerCAmelCase__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
594
import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase__ = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class _a ( lowerCamelCase_ , unittest.TestCase ): """simple docstring""" __SCREAMING_SNAKE_CASE = BartphoTokenizer __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True def __lowerCAmelCase ( self ): super().setUp() _lowercase =["▁This", "▁is", "▁a", "▁t", "est"] _lowercase =dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_ ) ) ) ) _lowercase ={"unk_token": "<unk>"} _lowercase =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["monolingual_vocab_file"] ) with open(self.monolingual_vocab_file , "w" , encoding="utf-8" ) as fp: for token in vocab_tokens: fp.write(F'''{token} {vocab_tokens[token]}\n''' ) _lowercase =BartphoTokenizer(lowerCAmelCase_ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCAmelCase ( self , **lowerCAmelCase_ ): kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase_ ) def __lowerCAmelCase ( self , lowerCAmelCase_ ): _lowercase ="This is a là test" _lowercase ="This is a<unk><unk> test" return input_text, output_text def __lowerCAmelCase ( self ): _lowercase =BartphoTokenizer(lowerCAmelCase_ , self.monolingual_vocab_file , **self.special_tokens_map ) _lowercase ="This is a là test" _lowercase ="▁This ▁is ▁a ▁l à ▁t est".split() _lowercase =tokenizer.tokenize(lowerCAmelCase_ ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) _lowercase =tokens + [tokenizer.unk_token] _lowercase =[4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_ ) , lowerCAmelCase_ )
594
1
'''simple docstring''' import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets UpperCAmelCase__ :List[Any] = datasets.logging.get_logger(__name__) UpperCAmelCase__ :Tuple = """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ UpperCAmelCase__ :Any = """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ UpperCAmelCase__ :int = """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ UpperCAmelCase__ :Dict = { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE ( datasets.Metric ): def a_ ( self : str ): """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , ) def a_ ( self : Union[str, Any] , A__ : Optional[int] ): """simple docstring""" if self.config_name == "default": logger.warning( """Using default BLEURT-Base checkpoint for sequence maximum length 128. """ """You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" ) __lowerCamelCase : Dict = """bleurt-base-128""" if self.config_name.lower() in CHECKPOINT_URLS: __lowerCamelCase : str = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: __lowerCamelCase : Dict = self.config_name.upper() else: raise KeyError( f"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}" ) # download the model checkpoint specified by self.config_name and set up the scorer __lowerCamelCase : Dict = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) __lowerCamelCase : Any = score.BleurtScorer(os.path.join(A__ , A__ ) ) def a_ ( self : List[Any] , A__ : Optional[int] , A__ : Dict ): """simple docstring""" __lowerCamelCase : str = self.scorer.score(references=A__ , candidates=A__ ) return {"scores": scores}
150
'''simple docstring''' from typing import List from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ :List[str] = logging.get_logger(__name__) UpperCAmelCase__ :List[str] = { """snap-research/efficientformer-l1-300""": ( """https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json""" ), } class SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): snake_case__ : Dict = 'efficientformer' def __init__( self : Optional[Any] , A__ : List[int] = [3, 2, 6, 4] , A__ : List[int] = [48, 96, 224, 448] , A__ : List[bool] = [True, True, True, True] , A__ : int = 448 , A__ : int = 32 , A__ : int = 4 , A__ : int = 7 , A__ : int = 5 , A__ : int = 8 , A__ : int = 4 , A__ : float = 0.0 , A__ : int = 16 , A__ : int = 3 , A__ : int = 3 , A__ : int = 3 , A__ : int = 2 , A__ : int = 1 , A__ : float = 0.0 , A__ : int = 1 , A__ : bool = True , A__ : bool = True , A__ : float = 1e-5 , A__ : str = "gelu" , A__ : float = 0.02 , A__ : float = 1e-1_2 , A__ : int = 224 , A__ : float = 1e-0_5 , **A__ : Union[str, Any] , ): """simple docstring""" super().__init__(**A__ ) __lowerCamelCase : Optional[int] = hidden_act __lowerCamelCase : Optional[Any] = hidden_dropout_prob __lowerCamelCase : Any = hidden_sizes __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : List[Any] = num_attention_heads __lowerCamelCase : Union[str, Any] = initializer_range __lowerCamelCase : Tuple = layer_norm_eps __lowerCamelCase : Optional[int] = patch_size __lowerCamelCase : Union[str, Any] = num_channels __lowerCamelCase : Dict = depths __lowerCamelCase : Optional[Any] = mlp_expansion_ratio __lowerCamelCase : int = downsamples __lowerCamelCase : List[str] = dim __lowerCamelCase : Dict = key_dim __lowerCamelCase : List[Any] = attention_ratio __lowerCamelCase : str = resolution __lowerCamelCase : Union[str, Any] = pool_size __lowerCamelCase : Optional[int] = downsample_patch_size __lowerCamelCase : Any = downsample_stride __lowerCamelCase : Dict = downsample_pad __lowerCamelCase : int = drop_path_rate __lowerCamelCase : Tuple = num_metaad_blocks __lowerCamelCase : Optional[Any] = distillation __lowerCamelCase : List[Any] = use_layer_scale __lowerCamelCase : List[Any] = layer_scale_init_value __lowerCamelCase : int = image_size __lowerCamelCase : Dict = batch_norm_eps
150
1
import colorsys from PIL import Image # type: ignore def A (__A : Dict , __A : List[str] , __A : Optional[Any] ) -> float: """simple docstring""" UpperCAmelCase_ = x UpperCAmelCase_ = y for step in range(__A ): # noqa: B007 UpperCAmelCase_ = a * a - b * b + x UpperCAmelCase_ = 2 * a * b + y UpperCAmelCase_ = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def A (__A : Optional[Any] ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def A (__A : List[Any] ) -> tuple: """simple docstring""" if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(__A , 1 , 1 ) ) def A (__A : int = 800 , __A : Optional[int] = 600 , __A : Union[str, Any] = -0.6 , __A : Union[str, Any] = 0 , __A : Optional[Any] = 3.2 , __A : List[str] = 50 , __A : List[str] = True , ) -> Image.Image: """simple docstring""" UpperCAmelCase_ = Image.new('''RGB''' , (image_width, image_height) ) UpperCAmelCase_ = img.load() # loop through the image-coordinates for image_x in range(__A ): for image_y in range(__A ): # determine the figure-coordinates based on the image-coordinates UpperCAmelCase_ = figure_width / image_width * image_height UpperCAmelCase_ = figure_center_x + (image_x / image_width - 0.5) * figure_width UpperCAmelCase_ = figure_center_y + (image_y / image_height - 0.5) * figure_height UpperCAmelCase_ = get_distance(__A , __A , __A ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: UpperCAmelCase_ = get_color_coded_rgb(__A ) else: UpperCAmelCase_ = get_black_and_white_rgb(__A ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure snake_case_ : Tuple = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
718
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : Optional[Any] = logging.get_logger(__name__) snake_case_ : Optional[int] = { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json", "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json", } class __snake_case ( a ): UpperCAmelCase__ : Any = '''roberta''' def __init__( self : Tuple , _snake_case : int=50265 , _snake_case : Dict=768 , _snake_case : Union[str, Any]=12 , _snake_case : Tuple=12 , _snake_case : Optional[Any]=3072 , _snake_case : str="gelu" , _snake_case : Tuple=0.1 , _snake_case : str=0.1 , _snake_case : Tuple=512 , _snake_case : List[str]=2 , _snake_case : Optional[int]=0.0_2 , _snake_case : Tuple=1e-12 , _snake_case : Tuple=1 , _snake_case : int=0 , _snake_case : str=2 , _snake_case : Tuple="absolute" , _snake_case : Any=True , _snake_case : Union[str, Any]=None , **_snake_case : Any , ): """simple docstring""" super().__init__(pad_token_id=_snake_case , bos_token_id=_snake_case , eos_token_id=_snake_case , **_snake_case) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = hidden_act UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = position_embedding_type UpperCAmelCase_ = use_cache UpperCAmelCase_ = classifier_dropout class __snake_case ( a ): @property def lowerCamelCase ( self : Tuple): """simple docstring""" if self.task == "multiple-choice": UpperCAmelCase_ = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCAmelCase_ = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ])
169
0
from __future__ import annotations def SCREAMING_SNAKE_CASE ( __lowerCAmelCase , __lowerCAmelCase = None , __lowerCAmelCase = None ) -> None: if start is None: snake_case__ = 0 if end is None: snake_case__ = len(__lowerCAmelCase ) - 1 if start >= end: return snake_case__ = (start + end) // 2 slowsort(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) slowsort(__lowerCAmelCase , mid + 1 , __lowerCAmelCase ) if sequence[end] < sequence[mid]: snake_case__ , snake_case__ = sequence[mid], sequence[end] slowsort(__lowerCAmelCase , __lowerCAmelCase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
33
def a_ (__A , __A , __A , __A ) -> int: """simple docstring""" __a , __a : Any = len(__A ), len(grid[0] ) if ( min(__A , __A ) < 0 or row == row_length or col == col_length or (row, col) in visit or grid[row][col] == 1 ): return 0 if row == row_length - 1 and col == col_length - 1: return 1 visit.add((row, col) ) __a : Dict = 0 count += depth_first_search(__A , row + 1 , __A , __A ) count += depth_first_search(__A , row - 1 , __A , __A ) count += depth_first_search(__A , __A , col + 1 , __A ) count += depth_first_search(__A , __A , col - 1 , __A ) visit.remove((row, col) ) return count if __name__ == "__main__": import doctest doctest.testmod()
351
0
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 _UpperCAmelCase : str = logging.get_logger(__name__) _UpperCAmelCase : Optional[int] = "▁" _UpperCAmelCase : Dict = { "vocab_file": "vocab.json", "spm_file": "sentencepiece.bpe.model", "tokenizer_config_file": "tokenizer_config.json", } _UpperCAmelCase : Optional[int] = { "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", }, } _UpperCAmelCase : int = { "facebook/m2m100_418M": 1024, } # fmt: off _UpperCAmelCase : Union[str, Any] = { "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 __lowerCAmelCase ( lowerCAmelCase): _a = VOCAB_FILES_NAMES _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = PRETRAINED_VOCAB_FILES_MAP _a = ['''input_ids''', '''attention_mask'''] _a = [] _a = [] def __init__( self: List[str] , _lowerCAmelCase: List[Any] , _lowerCAmelCase: Union[str, Any] , _lowerCAmelCase: Optional[Any]=None , _lowerCAmelCase: Tuple=None , _lowerCAmelCase: List[str]="<s>" , _lowerCAmelCase: Optional[int]="</s>" , _lowerCAmelCase: Any="</s>" , _lowerCAmelCase: str="<pad>" , _lowerCAmelCase: int="<unk>" , _lowerCAmelCase: Optional[int]="m2m100" , _lowerCAmelCase: Optional[Dict[str, Any]] = None , _lowerCAmelCase: Optional[Any]=8 , **_lowerCAmelCase: Optional[Any] , ): lowercase :Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs lowercase :str = language_codes lowercase :Any = FAIRSEQ_LANGUAGE_CODES[language_codes] lowercase :Tuple = {lang_code: F"__{lang_code}__" for lang_code in fairseq_language_code} lowercase :Dict = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(_lowerCAmelCase ) for lang_code in fairseq_language_code if self.get_lang_token(_lowerCAmelCase ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=_lowerCAmelCase , tgt_lang=_lowerCAmelCase , bos_token=_lowerCAmelCase , eos_token=_lowerCAmelCase , sep_token=_lowerCAmelCase , unk_token=_lowerCAmelCase , pad_token=_lowerCAmelCase , language_codes=_lowerCAmelCase , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=_lowerCAmelCase , **_lowerCAmelCase , ) lowercase :Tuple = vocab_file lowercase :List[Any] = load_json(_lowerCAmelCase ) lowercase :Dict = {v: k for k, v in self.encoder.items()} lowercase :Any = spm_file lowercase :Any = load_spm(_lowerCAmelCase , self.sp_model_kwargs ) lowercase :str = len(self.encoder ) lowercase :List[Any] = { self.get_lang_token(_lowerCAmelCase ): self.encoder_size + i for i, lang_code in enumerate(_lowerCAmelCase ) } lowercase :List[str] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(_lowerCAmelCase )} lowercase :Any = {v: k for k, v in self.lang_token_to_id.items()} lowercase :List[str] = src_lang if src_lang is not None else "en" lowercase :List[Any] = tgt_lang lowercase :Optional[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowercase :Union[str, Any] = num_madeup_words @property def SCREAMING_SNAKE_CASE ( self: Optional[Any] ): return len(self.encoder ) + len(self.lang_token_to_id ) @property def SCREAMING_SNAKE_CASE ( self: str ): return self._src_lang @src_lang.setter def SCREAMING_SNAKE_CASE ( self: List[str] , _lowerCAmelCase: str ): lowercase :List[Any] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def SCREAMING_SNAKE_CASE ( self: str , _lowerCAmelCase: str ): return self.sp_model.encode(_lowerCAmelCase , out_type=_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: Optional[int] , _lowerCAmelCase: Dict ): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(_lowerCAmelCase , self.encoder[self.unk_token] ) def SCREAMING_SNAKE_CASE ( self: List[str] , _lowerCAmelCase: int ): if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(_lowerCAmelCase , self.unk_token ) def SCREAMING_SNAKE_CASE ( self: Dict , _lowerCAmelCase: Optional[int] ): lowercase :Tuple = [] lowercase :Optional[Any] = "" 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(_lowerCAmelCase ) + token lowercase :Dict = [] else: current_sub_tokens.append(_lowerCAmelCase ) out_string += self.sp_model.decode(_lowerCAmelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _lowerCAmelCase: List[int] , _lowerCAmelCase: Optional[List[int]] = None , _lowerCAmelCase: bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCAmelCase , token_ids_a=_lowerCAmelCase , already_has_special_tokens=_lowerCAmelCase ) lowercase :Optional[int] = [1] * len(self.prefix_tokens ) lowercase :Optional[int] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(_lowerCAmelCase )) + suffix_ones return prefix_ones + ([0] * len(_lowerCAmelCase )) + ([0] * len(_lowerCAmelCase )) + suffix_ones def SCREAMING_SNAKE_CASE ( self: Dict , _lowerCAmelCase: List[int] , _lowerCAmelCase: Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def SCREAMING_SNAKE_CASE ( self: Any ): lowercase :Tuple = {self.convert_ids_to_tokens(_lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self: Any ): lowercase :Optional[int] = self.__dict__.copy() lowercase :Optional[Any] = None return state def __setstate__( self: Union[str, Any] , _lowerCAmelCase: Dict ): lowercase :Optional[Any] = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowercase :str = {} lowercase :str = load_spm(self.spm_file , self.sp_model_kwargs ) def SCREAMING_SNAKE_CASE ( self: Optional[Any] , _lowerCAmelCase: str , _lowerCAmelCase: Optional[str] = None ): lowercase :Tuple = Path(_lowerCAmelCase ) if not save_dir.is_dir(): raise OSError(F"{save_directory} should be a directory" ) lowercase :List[Any] = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) lowercase :Any = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , _lowerCAmelCase ) if os.path.abspath(self.spm_file ) != os.path.abspath(_lowerCAmelCase ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , _lowerCAmelCase ) elif not os.path.isfile(self.spm_file ): with open(_lowerCAmelCase , "wb" ) as fi: lowercase :Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_lowerCAmelCase ) return (str(_lowerCAmelCase ), str(_lowerCAmelCase )) def SCREAMING_SNAKE_CASE ( self: Union[str, Any] , _lowerCAmelCase: List[str] , _lowerCAmelCase: str = "en" , _lowerCAmelCase: Optional[List[str]] = None , _lowerCAmelCase: str = "ro" , **_lowerCAmelCase: List[str] , ): lowercase :Optional[int] = src_lang lowercase :Optional[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(_lowerCAmelCase , _lowerCAmelCase , **_lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self: Optional[Any] , _lowerCAmelCase: Optional[int] , _lowerCAmelCase: Optional[str] , _lowerCAmelCase: Optional[str] , **_lowerCAmelCase: Union[str, Any] ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) lowercase :Tuple = src_lang lowercase :List[str] = self(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase , **_lowerCAmelCase ) lowercase :List[Any] = self.get_lang_id(_lowerCAmelCase ) lowercase :Optional[int] = tgt_lang_id return inputs def SCREAMING_SNAKE_CASE ( self: str ): self.set_src_lang_special_tokens(self.src_lang ) def SCREAMING_SNAKE_CASE ( self: Tuple ): self.set_tgt_lang_special_tokens(self.tgt_lang ) def SCREAMING_SNAKE_CASE ( self: Optional[int] , _lowerCAmelCase: str ): lowercase :int = self.get_lang_token(_lowerCAmelCase ) lowercase :Union[str, Any] = self.lang_token_to_id[lang_token] lowercase :Dict = [self.cur_lang_id] lowercase :int = [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self: List[str] , _lowerCAmelCase: str ): lowercase :Optional[int] = self.get_lang_token(_lowerCAmelCase ) lowercase :List[Any] = self.lang_token_to_id[lang_token] lowercase :str = [self.cur_lang_id] lowercase :List[str] = [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self: List[Any] , _lowerCAmelCase: str ): return self.lang_code_to_token[lang] def SCREAMING_SNAKE_CASE ( self: Optional[int] , _lowerCAmelCase: str ): lowercase :Dict = self.get_lang_token(_lowerCAmelCase ) return self.lang_token_to_id[lang_token] def UpperCAmelCase__ ( lowerCamelCase, lowerCamelCase ): lowercase :Optional[int] = sentencepiece.SentencePieceProcessor(**lowerCamelCase ) spm.Load(str(lowerCamelCase ) ) return spm def UpperCAmelCase__ ( lowerCamelCase ): with open(lowerCamelCase, "r" ) as f: return json.load(lowerCamelCase ) def UpperCAmelCase__ ( lowerCamelCase, lowerCamelCase ): with open(lowerCamelCase, "w" ) as f: json.dump(lowerCamelCase, lowerCamelCase, indent=2 )
712
def UpperCAmelCase__ ( lowerCamelCase, lowerCamelCase ): if discount_rate < 0: raise ValueError("Discount rate cannot be negative" ) if not cash_flows: raise ValueError("Cash flows list cannot be empty" ) lowercase :Dict = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase ) ) return round(lowerCamelCase, ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
453
0
import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class a ( unittest.TestCase ): """simple docstring""" def __init__( self , lowerCAmelCase_ , lowerCAmelCase_=13 , lowerCAmelCase_=7 , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=True , lowerCAmelCase_=99 , lowerCAmelCase_=32 , lowerCAmelCase_=5 , lowerCAmelCase_=4 , lowerCAmelCase_=37 , lowerCAmelCase_="gelu" , lowerCAmelCase_=0.1 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=16 , lowerCAmelCase_=2 , lowerCAmelCase_=0.02 , lowerCAmelCase_=4 , ) -> Optional[Any]: _A = parent _A = batch_size _A = seq_length _A = is_training _A = use_attention_mask _A = use_token_type_ids _A = use_labels _A = vocab_size _A = hidden_size _A = num_hidden_layers _A = num_attention_heads _A = intermediate_size _A = hidden_act _A = hidden_dropout_prob _A = attention_probs_dropout_prob _A = max_position_embeddings _A = type_vocab_size _A = type_sequence_label_size _A = initializer_range _A = num_choices def UpperCAmelCase ( self ) -> Union[str, Any]: _A = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _A = None if self.use_attention_mask: _A = random_attention_mask([self.batch_size, self.seq_length] ) _A = None if self.use_token_type_ids: _A = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _A = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase_ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def UpperCAmelCase ( self ) -> List[Any]: _A = self.prepare_config_and_inputs() _A , _A , _A , _A = config_and_inputs _A = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask} return config, inputs_dict def UpperCAmelCase ( self ) -> Any: _A = self.prepare_config_and_inputs() _A , _A , _A , _A = config_and_inputs _A = True _A = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _A = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class a ( __lowerCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase :List[str] = True lowerCamelCase :Optional[int] = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCAmelCase ( self ) -> Any: _A = FlaxBertModelTester(self ) @slow def UpperCAmelCase ( self ) -> str: # Only check this for base model, not necessary for all model classes. # This will also help speed-up tests. _A = FlaxBertModel.from_pretrained("""bert-base-cased""" ) _A = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCAmelCase_ )
401
import copy from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import ClassLabel, Features, Value from .base import TaskTemplate @dataclass(frozen=__lowerCAmelCase ) class a ( __lowerCAmelCase ): """simple docstring""" lowerCamelCase :str = field(default='''text-classification''' , metadata={'''include_in_asdict_even_if_is_default''': True} ) lowerCamelCase :ClassVar[Features] = Features({'''text''': Value('''string''' )} ) lowerCamelCase :ClassVar[Features] = Features({'''labels''': ClassLabel} ) lowerCamelCase :str = "text" lowerCamelCase :str = "labels" def UpperCAmelCase ( self , lowerCAmelCase_ ) -> Optional[int]: if self.label_column not in features: raise ValueError(F'''Column {self.label_column} is not present in features.''' ) if not isinstance(features[self.label_column] , lowerCAmelCase_ ): raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' ) _A = copy.deepcopy(self ) _A = self.label_schema.copy() _A = features[self.label_column] _A = label_schema return task_template @property def UpperCAmelCase ( self ) -> Dict[str, str]: return { self.text_column: "text", self.label_column: "labels", }
401
1
'''simple docstring''' import requests from bsa import BeautifulSoup def lowerCAmelCase_ ( lowerCamelCase = "AAPL" ): __magic_name__ : Any =F"https://in.finance.yahoo.com/quote/{symbol}?s={symbol}" __magic_name__ : List[str] =BeautifulSoup(requests.get(lowerCamelCase ).text , """html.parser""" ) __magic_name__ : Optional[Any] ="""My(6px) Pos(r) smartphone_Mt(6px)""" return soup.find("""div""" , class_=class_ ).find("""span""" ).text if __name__ == "__main__": for symbol in "AAPL AMZN IBM GOOG MSFT ORCL".split(): print(F"""Current {symbol:<4} stock price is {stock_price(symbol):>8}""")
707
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class __A : def __init__( self :Optional[int] , __snake_case :Optional[Any] , __snake_case :List[Any]=13 , __snake_case :str=7 , __snake_case :Tuple=True , __snake_case :Dict=True , __snake_case :Optional[Any]=True , __snake_case :str=True , __snake_case :int=99 , __snake_case :int=32 , __snake_case :Dict=2 , __snake_case :Optional[Any]=4 , __snake_case :Dict=37 , __snake_case :Optional[int]="gelu" , __snake_case :Tuple=0.1 , __snake_case :Tuple=0.1 , __snake_case :int=5_12 , __snake_case :int=16 , __snake_case :int=2 , __snake_case :Optional[int]=0.02 , __snake_case :Union[str, Any]=3 , __snake_case :Any=4 , __snake_case :str=None , __snake_case :str=0 , ): '''simple docstring''' __magic_name__ : Optional[int] =parent __magic_name__ : int =batch_size __magic_name__ : Any =seq_length __magic_name__ : List[str] =is_training __magic_name__ : Any =use_input_mask __magic_name__ : Union[str, Any] =use_token_type_ids __magic_name__ : Union[str, Any] =use_labels __magic_name__ : Optional[Any] =vocab_size __magic_name__ : Optional[Any] =hidden_size __magic_name__ : Optional[Any] =num_hidden_layers __magic_name__ : Optional[Any] =num_attention_heads __magic_name__ : Tuple =intermediate_size __magic_name__ : Tuple =hidden_act __magic_name__ : Tuple =hidden_dropout_prob __magic_name__ : Any =attention_probs_dropout_prob __magic_name__ : Union[str, Any] =max_position_embeddings __magic_name__ : int =type_vocab_size __magic_name__ : Optional[Any] =type_sequence_label_size __magic_name__ : Union[str, Any] =initializer_range __magic_name__ : Optional[Any] =num_labels __magic_name__ : Any =num_choices __magic_name__ : Optional[Any] =scope __magic_name__ : str =projection_dim def A__ ( self :Dict ): '''simple docstring''' __magic_name__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : Union[str, Any] =None if self.use_input_mask: # follow test_modeling_tf_ctrl.py __magic_name__ : List[Any] =random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : Optional[int] =None if self.use_token_type_ids: __magic_name__ : str =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : List[str] =None __magic_name__ : List[Any] =None __magic_name__ : List[str] =None if self.use_labels: __magic_name__ : str =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ : Union[str, Any] =ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ : Optional[int] =BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__snake_case , initializer_range=self.initializer_range , ) __magic_name__ : Dict =DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def A__ ( self :List[Any] , __snake_case :List[Any] , __snake_case :List[str] , __snake_case :Any , __snake_case :Any , __snake_case :Optional[Any] , __snake_case :Optional[Any] , __snake_case :List[str] ): '''simple docstring''' __magic_name__ : List[Any] =TFDPRContextEncoder(config=__snake_case ) __magic_name__ : Union[str, Any] =model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) __magic_name__ : str =model(__snake_case , token_type_ids=__snake_case ) __magic_name__ : Optional[int] =model(__snake_case ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def A__ ( self :int , __snake_case :str , __snake_case :Tuple , __snake_case :Optional[Any] , __snake_case :Optional[Any] , __snake_case :Tuple , __snake_case :List[Any] , __snake_case :int ): '''simple docstring''' __magic_name__ : int =TFDPRQuestionEncoder(config=__snake_case ) __magic_name__ : Union[str, Any] =model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) __magic_name__ : List[str] =model(__snake_case , token_type_ids=__snake_case ) __magic_name__ : Union[str, Any] =model(__snake_case ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def A__ ( self :List[Any] , __snake_case :List[str] , __snake_case :Optional[int] , __snake_case :str , __snake_case :Any , __snake_case :str , __snake_case :Optional[Any] , __snake_case :Dict ): '''simple docstring''' __magic_name__ : Optional[int] =TFDPRReader(config=__snake_case ) __magic_name__ : List[str] =model(__snake_case , attention_mask=__snake_case ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def A__ ( self :Optional[Any] ): '''simple docstring''' __magic_name__ : str =self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) : Union[str, Any] =config_and_inputs __magic_name__ : List[str] ={"""input_ids""": input_ids} return config, inputs_dict @require_tf class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): UpperCamelCase = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) UpperCamelCase = {"""feature-extraction""": TFDPRQuestionEncoder} if is_tf_available() else {} UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False UpperCamelCase = False def A__ ( self :Union[str, Any] ): '''simple docstring''' __magic_name__ : Union[str, Any] =TFDPRModelTester(self ) __magic_name__ : Optional[Any] =ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def A__ ( self :Dict ): '''simple docstring''' self.config_tester.run_common_tests() def A__ ( self :Tuple ): '''simple docstring''' __magic_name__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__snake_case ) def A__ ( self :List[Any] ): '''simple docstring''' __magic_name__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__snake_case ) def A__ ( self :Any ): '''simple docstring''' __magic_name__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__snake_case ) @slow def A__ ( self :Tuple ): '''simple docstring''' for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Dict =TFDPRContextEncoder.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Dict =TFDPRContextEncoder.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Union[str, Any] =TFDPRQuestionEncoder.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : List[str] =TFDPRReader.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) @require_tf class __A ( unittest.TestCase ): @slow def A__ ( self :Optional[Any] ): '''simple docstring''' __magic_name__ : int =TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) __magic_name__ : int =tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] __magic_name__ : Optional[Any] =model(__snake_case )[0] # embedding shape = (1, 768) # compare the actual values for a slice. __magic_name__ : Tuple =tf.constant( [ [ 0.03236253, 0.12753335, 0.16818509, 0.00279786, 0.3896933, 0.24264945, 0.2178971, -0.02335227, -0.08481959, -0.14324117, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1E-4 ) )
367
0
'''simple docstring''' import logging import os from .state import PartialState class SCREAMING_SNAKE_CASE (logging.LoggerAdapter ): @staticmethod def SCREAMING_SNAKE_CASE ( _UpperCAmelCase): '''simple docstring''' __A : Any = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase): '''simple docstring''' if PartialState._shared_state == {}: raise RuntimeError( 'You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.') __A : List[Any] = kwargs.pop('main_process_only' , _UpperCAmelCase) __A : str = kwargs.pop('in_order' , _UpperCAmelCase) if self.isEnabledFor(_UpperCAmelCase): if self._should_log(_UpperCAmelCase): __A ,__A : Dict = self.process(_UpperCAmelCase , _UpperCAmelCase) self.logger.log(_UpperCAmelCase , _UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase) elif in_order: __A : Tuple = PartialState() for i in range(state.num_processes): if i == state.process_index: __A ,__A : Union[str, Any] = self.process(_UpperCAmelCase , _UpperCAmelCase) self.logger.log(_UpperCAmelCase , _UpperCAmelCase , *_UpperCAmelCase , **_UpperCAmelCase) state.wait_for_everyone() def _lowerCAmelCase ( __snake_case : str , __snake_case : str = None ) -> str: if log_level is None: __A : List[Any] = os.environ.get('ACCELERATE_LOG_LEVEL' , __snake_case ) __A : Dict = logging.getLogger(__snake_case ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__snake_case , {} )
8
# Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position snake_case_ = '2.13.1' import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse('3.7'): raise ImportWarning( 'To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.' ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( 'To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n' 'If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.' ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip snake_case_ = concatenate_datasets snake_case_ = DownloadConfig snake_case_ = DownloadManager snake_case_ = DownloadMode snake_case_ = DownloadConfig snake_case_ = DownloadMode snake_case_ = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
592
0
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
700
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL __UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) def lowercase_ ( __snake_case : Any , __snake_case : Any ) -> Any: '''simple docstring''' snake_case__ :Optional[Any] = b.T snake_case__ :Optional[Any] = np.sum(np.square(__snake_case ) , axis=1 ) snake_case__ :Tuple = np.sum(np.square(__snake_case ) , axis=0 ) snake_case__ :Union[str, Any] = np.matmul(__snake_case , __snake_case ) snake_case__ :Union[str, Any] = aa[:, None] - 2 * ab + ba[None, :] return d def lowercase_ ( __snake_case : Optional[Any] , __snake_case : int ) -> Any: '''simple docstring''' snake_case__ :Optional[Any] = x.reshape(-1 , 3 ) snake_case__ :List[str] = squared_euclidean_distance(__snake_case , __snake_case ) return np.argmin(__snake_case , axis=1 ) class _snake_case ( _A ): _A = ['pixel_values'] def __init__( self ,UpperCamelCase = None ,UpperCamelCase = True ,UpperCamelCase = None ,UpperCamelCase = PILImageResampling.BILINEAR ,UpperCamelCase = True ,UpperCamelCase = True ,**UpperCamelCase ,) -> None: super().__init__(**UpperCamelCase ) snake_case__ :List[Any] = size if size is not None else {"height": 256, "width": 256} snake_case__ :str = get_size_dict(UpperCamelCase ) snake_case__ :Dict = np.array(UpperCamelCase ) if clusters is not None else None snake_case__ :str = do_resize snake_case__ :List[str] = size snake_case__ :List[Any] = resample snake_case__ :Union[str, Any] = do_normalize snake_case__ :int = do_color_quantize def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase ,UpperCamelCase = PILImageResampling.BILINEAR ,UpperCamelCase = None ,**UpperCamelCase ,) -> np.ndarray: snake_case__ :List[str] = get_size_dict(UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'Size dictionary must contain both height and width keys. Got {size.keys()}' ) return resize( UpperCamelCase ,size=(size["height"], size["width"]) ,resample=UpperCamelCase ,data_format=UpperCamelCase ,**UpperCamelCase ) def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase = None ,) -> np.ndarray: snake_case__ :Tuple = rescale(image=UpperCamelCase ,scale=1 / 127.5 ,data_format=UpperCamelCase ) snake_case__ :List[Any] = image - 1 return image def lowerCAmelCase_ ( self ,UpperCamelCase ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = None ,UpperCamelCase = ChannelDimension.FIRST ,**UpperCamelCase ,) -> PIL.Image.Image: snake_case__ :Optional[int] = do_resize if do_resize is not None else self.do_resize snake_case__ :int = size if size is not None else self.size snake_case__ :Tuple = get_size_dict(UpperCamelCase ) snake_case__ :str = resample if resample is not None else self.resample snake_case__ :Dict = do_normalize if do_normalize is not None else self.do_normalize snake_case__ :Tuple = do_color_quantize if do_color_quantize is not None else self.do_color_quantize snake_case__ :List[Any] = clusters if clusters is not None else self.clusters snake_case__ :str = np.array(UpperCamelCase ) snake_case__ :int = make_list_of_images(UpperCamelCase ) if not valid_images(UpperCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_color_quantize and clusters is None: raise ValueError("Clusters must be specified if do_color_quantize is True." ) # All transformations expect numpy arrays. snake_case__ :Union[str, Any] = [to_numpy_array(UpperCamelCase ) for image in images] if do_resize: snake_case__ :int = [self.resize(image=UpperCamelCase ,size=UpperCamelCase ,resample=UpperCamelCase ) for image in images] if do_normalize: snake_case__ :Any = [self.normalize(image=UpperCamelCase ) for image in images] if do_color_quantize: snake_case__ :Optional[Any] = [to_channel_dimension_format(UpperCamelCase ,ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) snake_case__ :Union[str, Any] = np.array(UpperCamelCase ) snake_case__ :Optional[int] = color_quantize(UpperCamelCase ,UpperCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) snake_case__ :List[Any] = images.shape[0] snake_case__ :str = images.reshape(UpperCamelCase ,-1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. snake_case__ :Any = list(UpperCamelCase ) else: snake_case__ :List[str] = [to_channel_dimension_format(UpperCamelCase ,UpperCamelCase ) for image in images] snake_case__ :List[str] = {"input_ids": images} return BatchFeature(data=UpperCamelCase ,tensor_type=UpperCamelCase )
57
0
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() UpperCamelCase__ : Union[str, Any] = logging.get_logger(__name__) def __UpperCAmelCase ( lowerCamelCase_ : Optional[int] , lowerCamelCase_ : Optional[int] , lowerCamelCase_ : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : str = UniSpeechSatForSequenceClassification.from_pretrained(lowerCamelCase_ , config=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = downstream_dict['projector.weight'] SCREAMING_SNAKE_CASE_ : Tuple = downstream_dict['projector.bias'] SCREAMING_SNAKE_CASE_ : List[str] = downstream_dict['model.post_net.linear.weight'] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict['model.post_net.linear.bias'] return model def __UpperCAmelCase ( lowerCamelCase_ : str , lowerCamelCase_ : List[str] , lowerCamelCase_ : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(lowerCamelCase_ , config=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = downstream_dict['model.linear.weight'] SCREAMING_SNAKE_CASE_ : str = downstream_dict['model.linear.bias'] return model def __UpperCAmelCase ( lowerCamelCase_ : List[str] , lowerCamelCase_ : str , lowerCamelCase_ : Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = UniSpeechSatForXVector.from_pretrained(lowerCamelCase_ , config=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Tuple = downstream_dict['connector.weight'] SCREAMING_SNAKE_CASE_ : Any = downstream_dict['connector.bias'] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): SCREAMING_SNAKE_CASE_ : Any = downstream_dict[ F'model.framelevel_feature_extractor.module.{i}.kernel.weight' ] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict[F'model.framelevel_feature_extractor.module.{i}.kernel.bias'] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict['model.utterancelevel_feature_extractor.linear1.weight'] SCREAMING_SNAKE_CASE_ : str = downstream_dict['model.utterancelevel_feature_extractor.linear1.bias'] SCREAMING_SNAKE_CASE_ : Dict = downstream_dict['model.utterancelevel_feature_extractor.linear2.weight'] SCREAMING_SNAKE_CASE_ : List[Any] = downstream_dict['model.utterancelevel_feature_extractor.linear2.bias'] SCREAMING_SNAKE_CASE_ : Optional[Any] = downstream_dict['objective.W'] return model @torch.no_grad() def __UpperCAmelCase ( lowerCamelCase_ : Any , lowerCamelCase_ : int , lowerCamelCase_ : List[str] , lowerCamelCase_ : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = torch.load(lowerCamelCase_ , map_location='cpu' ) SCREAMING_SNAKE_CASE_ : Tuple = checkpoint['Downstream'] SCREAMING_SNAKE_CASE_ : List[Any] = UniSpeechSatConfig.from_pretrained(lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : Optional[int] = WavaVecaFeatureExtractor.from_pretrained( lowerCamelCase_ , return_attention_mask=lowerCamelCase_ , do_normalize=lowerCamelCase_ ) SCREAMING_SNAKE_CASE_ : int = hf_config.architectures[0] if arch.endswith('ForSequenceClassification' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = convert_classification(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) elif arch.endswith('ForAudioFrameClassification' ): SCREAMING_SNAKE_CASE_ : Optional[Any] = convert_diarization(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) elif arch.endswith('ForXVector' ): SCREAMING_SNAKE_CASE_ : Any = convert_xvector(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) else: raise NotImplementedError(F'S3PRL weights conversion is not supported for {arch}' ) if hf_config.use_weighted_layer_sum: SCREAMING_SNAKE_CASE_ : str = checkpoint['Featurizer']['weights'] hf_feature_extractor.save_pretrained(lowerCamelCase_ ) hf_model.save_pretrained(lowerCamelCase_ ) if __name__ == "__main__": UpperCamelCase__ : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--base_model_name''', default=None, type=str, help='''Name of the huggingface pretrained base model.''' ) parser.add_argument('''--config_path''', default=None, type=str, help='''Path to the huggingface classifier config.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to the s3prl checkpoint.''') parser.add_argument('''--model_dump_path''', default=None, type=str, help='''Path to the final converted model.''') UpperCamelCase__ : List[str] = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
105
"""simple docstring""" from __future__ import annotations __UpperCAmelCase =1.6_0_2_1e-1_9 # units = C def __a ( A , A , A , ) -> tuple[str, float]: '''simple docstring''' 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()
337
0
def UpperCAmelCase__ ( A__ , A__ ) -> float: """simple docstring""" if digit_amount > 0: return round(number - int(A__ ) , A__ ) return number - int(A__ ) if __name__ == "__main__": print(decimal_isolate(1.5_3, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
704
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) SCREAMING_SNAKE_CASE_ : Optional[Any] = logging.getLogger(__name__) @dataclass class _A : __a = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) __a = field( default=__a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) __a = field( default=__a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) __a = field( default=__a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) __a = field(default=__a , metadata={'help': 'Whether tp freeze the encoder.'} ) __a = field(default=__a , metadata={'help': 'Whether to freeze the embeddings.'} ) @dataclass class _A : __a = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) __a = field( default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , ) __a = field( default=1024 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __a = field( default=128 , metadata={ 'help': ( 'The maximum total sequence length for target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __a = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for validation target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded. ' 'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ' 'during ``evaluate`` and ``predict``.' ) } , ) __a = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for test target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) __a = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} ) __a = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} ) __a = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} ) __a = field(default=__a , metadata={'help': 'Source language id for translation.'} ) __a = field(default=__a , metadata={'help': 'Target language id for translation.'} ) __a = field(default=__a , metadata={'help': '# num_beams to use for evaluation.'} ) __a = field( default=__a , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , ) def UpperCAmelCase__ ( A__ , A__ , A__ ) -> Union[str, Any]: """simple docstring""" logger.info(f'***** {split} metrics *****' ) for key in sorted(metrics.keys() ): logger.info(f' {key} = {metrics[key]}' ) save_json(A__ , os.path.join(A__ , f'{split}_results.json' ) ) def UpperCAmelCase__ ( ) -> List[str]: """simple docstring""" # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. lowerCamelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_args_into_dataclasses() check_output_dir(A__ ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info("Training/evaluation parameters %s" , A__ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. lowerCamelCase__ = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowerCamelCase__ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout") for p in extra_model_params: if getattr(A__ , A__ , A__ ): assert hasattr(A__ , A__ ), f'({config.__class__.__name__}) doesn\'t have a `{p}` attribute' setattr(A__ , A__ , getattr(A__ , A__ ) ) lowerCamelCase__ = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) lowerCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=A__ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(A__ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: lowerCamelCase__ = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(A__ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(A__ , A__ ): lowerCamelCase__ = tokenizer.lang_code_to_id[data_args.tgt_lang] else: lowerCamelCase__ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(A__ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) lowerCamelCase__ = SeqaSeqDataset # Get datasets lowerCamelCase__ = ( dataset_class( A__ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_train else None ) lowerCamelCase__ = ( dataset_class( A__ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) lowerCamelCase__ = ( dataset_class( A__ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , ) if training_args.do_predict else None ) # Initialize our Trainer lowerCamelCase__ = ( build_compute_metrics_fn(data_args.task , A__ ) if training_args.predict_with_generate else None ) lowerCamelCase__ = SeqaSeqTrainer( model=A__ , args=A__ , data_args=A__ , train_dataset=A__ , eval_dataset=A__ , data_collator=SeqaSeqDataCollator( A__ , A__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=A__ , tokenizer=A__ , ) lowerCamelCase__ = {} # Training if training_args.do_train: logger.info("*** Train ***" ) lowerCamelCase__ = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) lowerCamelCase__ = train_result.metrics lowerCamelCase__ = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics("train" , A__ , training_args.output_dir ) all_metrics.update(A__ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***" ) lowerCamelCase__ = trainer.evaluate(metric_key_prefix="val" ) lowerCamelCase__ = data_args.n_val lowerCamelCase__ = round(metrics["val_loss"] , 4 ) if trainer.is_world_process_zero(): handle_metrics("val" , A__ , training_args.output_dir ) all_metrics.update(A__ ) if training_args.do_predict: logger.info("*** Predict ***" ) lowerCamelCase__ = trainer.predict(test_dataset=A__ , metric_key_prefix="test" ) lowerCamelCase__ = test_output.metrics lowerCamelCase__ = data_args.n_test if trainer.is_world_process_zero(): lowerCamelCase__ = round(metrics["test_loss"] , 4 ) handle_metrics("test" , A__ , training_args.output_dir ) all_metrics.update(A__ ) if training_args.predict_with_generate: lowerCamelCase__ = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=A__ , clean_up_tokenization_spaces=A__ ) lowerCamelCase__ = lmap(str.strip , A__ ) write_txt_file(A__ , os.path.join(training_args.output_dir , "test_generations.txt" ) ) if trainer.is_world_process_zero(): save_json(A__ , os.path.join(training_args.output_dir , "all_results.json" ) ) return all_metrics def UpperCAmelCase__ ( A__ ) -> Any: """simple docstring""" # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
274
0
"""simple docstring""" def _snake_case ( snake_case__ : str ): assert column_title.isupper() A = 0 A = len(snake_case__ ) - 1 A = 0 while index >= 0: A = (ord(column_title[index] ) - 64) * pow(26 , snake_case__ ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
91
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: __A : Optional[int] = None __A : Union[str, Any] = logging.get_logger(__name__) __A : List[Any] = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} __A : str = { "vocab_file": { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model", "google/bigbird-roberta-large": ( "https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model" ), "google/bigbird-base-trivia-itc": ( "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model" ), }, "tokenizer_file": { "google/bigbird-roberta-base": ( "https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json" ), "google/bigbird-roberta-large": ( "https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json" ), "google/bigbird-base-trivia-itc": ( "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json" ), }, } __A : List[str] = { "google/bigbird-roberta-base": 4_096, "google/bigbird-roberta-large": 4_096, "google/bigbird-base-trivia-itc": 4_096, } __A : Tuple = "▁" class __lowerCAmelCase ( _UpperCamelCase): '''simple docstring''' __magic_name__ : Dict = VOCAB_FILES_NAMES __magic_name__ : Any = PRETRAINED_VOCAB_FILES_MAP __magic_name__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ : List[Any] = BigBirdTokenizer __magic_name__ : Any = ["""input_ids""", """attention_mask"""] __magic_name__ : List[int] = [] def __init__( self : str , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Union[str, Any]="<unk>" , UpperCamelCase__ : str="<s>" , UpperCamelCase__ : int="</s>" , UpperCamelCase__ : Optional[int]="<pad>" , UpperCamelCase__ : Optional[Any]="[SEP]" , UpperCamelCase__ : List[Any]="[MASK]" , UpperCamelCase__ : str="[CLS]" , **UpperCamelCase__ : List[Any] , ): A__ : Optional[int] =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else bos_token A__ : Optional[Any] =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else eos_token A__ : Optional[int] =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else unk_token A__ : int =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else pad_token A__ : str =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else cls_token A__ : List[Any] =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A__ : str =AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token super().__init__( UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , **UpperCamelCase__ , ) A__ : List[Any] =vocab_file A__ : Optional[int] =False if not self.vocab_file else True def _UpperCAmelCase ( self : str , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): A__ : Tuple =[self.sep_token_id] A__ : str =[self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _UpperCAmelCase ( self : Optional[int] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase__ )) + [1] return [1] + ([0] * len(UpperCamelCase__ )) + [1] + ([0] * len(UpperCamelCase__ )) + [1] def _UpperCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ): A__ : Tuple =[self.sep_token_id] A__ : Dict =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return A__ : List[str] =os.path.join( UpperCamelCase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase__ ): copyfile(self.vocab_file , UpperCamelCase__ ) return (out_vocab_file,)
656
0
import math def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ): return math.pow(__lowerCamelCase , 2 ) - a def lowerCAmelCase_ ( __lowerCamelCase ): return 2 * x def lowerCAmelCase_ ( __lowerCamelCase ): __snake_case : List[Any] = 2.0 while start <= a: __snake_case : Union[str, Any] = math.pow(__lowerCamelCase , 2 ) return start def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase = 9_9_9_9 , __lowerCamelCase = 0.0_0_0_0_0_0_0_0_0_0_0_0_0_1 ): if a < 0: raise ValueError("math domain error" ) __snake_case : Optional[Any] = get_initial_point(__lowerCamelCase ) for _ in range(__lowerCamelCase ): __snake_case : Tuple = value __snake_case : int = value - fx(__lowerCamelCase , __lowerCamelCase ) / fx_derivative(__lowerCamelCase ) if abs(prev_value - value ) < tolerance: return value return value if __name__ == "__main__": from doctest import testmod testmod()
203
import gc import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DiffusionPipeline, EulerDiscreteScheduler, StableDiffusionXLImgaImgPipeline, UNetaDConditionModel, ) from diffusers.utils import floats_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = StableDiffusionXLImgaImgPipeline __UpperCAmelCase : Any = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} __UpperCAmelCase : Dict = PipelineTesterMixin.required_optional_params - {"latents"} __UpperCAmelCase : Union[str, Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __UpperCAmelCase : Tuple = IMAGE_TO_IMAGE_IMAGE_PARAMS __UpperCAmelCase : str = IMAGE_TO_IMAGE_IMAGE_PARAMS def __snake_case ( self : Optional[Any] ) -> Tuple: torch.manual_seed(0 ) __snake_case : Optional[int] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , attention_head_dim=(2, 4) , use_linear_projection=lowerCamelCase , addition_embed_type="text_time" , addition_time_embed_dim=8 , transformer_layers_per_block=(1, 2) , projection_class_embeddings_input_dim=80 , cross_attention_dim=64 , ) __snake_case : Tuple = EulerDiscreteScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , steps_offset=1 , beta_schedule="scaled_linear" , timestep_spacing="leading" , ) torch.manual_seed(0 ) __snake_case : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , sample_size=128 , ) torch.manual_seed(0 ) __snake_case : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act="gelu" , projection_dim=32 , ) __snake_case : List[str] = CLIPTextModel(lowerCamelCase ) __snake_case : Any = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=lowerCamelCase ) __snake_case : List[str] = CLIPTextModelWithProjection(lowerCamelCase ) __snake_case : List[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" , local_files_only=lowerCamelCase ) __snake_case : Optional[int] = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_encoder_2": text_encoder_a, "tokenizer_2": tokenizer_a, # "safety_checker": None, # "feature_extractor": None, } return components def __snake_case ( self : Optional[Any] , lowerCamelCase : List[Any] , lowerCamelCase : List[Any]=0 ) -> Union[str, Any]: __snake_case : int = floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase ) ).to(lowerCamelCase ) __snake_case : Any = image / 2 + 0.5 if str(lowerCamelCase ).startswith("mps" ): __snake_case : Dict = torch.manual_seed(lowerCamelCase ) else: __snake_case : int = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) __snake_case : Optional[Any] = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "numpy", "strength": 0.75, } return inputs def __snake_case ( self : Dict ) -> Any: __snake_case : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator __snake_case : Any = self.get_dummy_components() __snake_case : int = StableDiffusionXLImgaImgPipeline(**lowerCamelCase ) __snake_case : List[str] = sd_pipe.to(lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : Tuple = self.get_dummy_inputs(lowerCamelCase ) __snake_case : Dict = sd_pipe(**lowerCamelCase ).images __snake_case : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __snake_case : str = np.array([0.46_56, 0.48_40, 0.44_39, 0.66_98, 0.55_74, 0.45_24, 0.57_99, 0.59_43, 0.51_65] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __snake_case ( self : str ) -> Optional[Any]: super().test_attention_slicing_forward_pass(expected_max_diff=3E-3 ) def __snake_case ( self : Any ) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) def __snake_case ( self : str ) -> Optional[int]: pass def __snake_case ( self : Tuple ) -> Union[str, Any]: __snake_case : str = self.get_dummy_components() __snake_case : List[Any] = StableDiffusionXLImgaImgPipeline(**lowerCamelCase ) __snake_case : Optional[Any] = sd_pipe.to(lowerCamelCase ) __snake_case : int = sd_pipe.to(lowerCamelCase ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase ) # forward without prompt embeds __snake_case : List[str] = self.get_dummy_inputs(lowerCamelCase ) __snake_case : str = 3 * ["this is a negative prompt"] __snake_case : Any = negative_prompt __snake_case : Optional[Any] = 3 * [inputs["prompt"]] __snake_case : int = sd_pipe(**lowerCamelCase ) __snake_case : List[Any] = output.images[0, -3:, -3:, -1] # forward with prompt embeds __snake_case : List[Any] = self.get_dummy_inputs(lowerCamelCase ) __snake_case : Optional[Any] = 3 * ["this is a negative prompt"] __snake_case : int = 3 * [inputs.pop("prompt" )] ( ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ( __snake_case ) , ) : Dict = sd_pipe.encode_prompt(lowerCamelCase , negative_prompt=lowerCamelCase ) __snake_case : Tuple = sd_pipe( **lowerCamelCase , prompt_embeds=lowerCamelCase , negative_prompt_embeds=lowerCamelCase , pooled_prompt_embeds=lowerCamelCase , negative_pooled_prompt_embeds=lowerCamelCase , ) __snake_case : List[str] = output.images[0, -3:, -3:, -1] # make sure that it's equal assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4 @slow @require_torch_gpu class a (unittest.TestCase ): """simple docstring""" def __snake_case ( self : Optional[int] ) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def __snake_case ( self : Optional[Any] , lowerCamelCase : Any , lowerCamelCase : Optional[Any]="cpu" , lowerCamelCase : str=torch.floataa , lowerCamelCase : int=0 ) -> Dict: __snake_case : int = torch.Generator(device=lowerCamelCase ).manual_seed(lowerCamelCase ) __snake_case : Optional[Any] = np.random.RandomState(lowerCamelCase ).standard_normal((1, 4, 64, 64) ) __snake_case : Optional[Any] = torch.from_numpy(lowerCamelCase ).to(device=lowerCamelCase , dtype=lowerCamelCase ) __snake_case : List[str] = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def __snake_case ( self : str ) -> Any: __snake_case : List[str] = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base" ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __snake_case : int = self.get_inputs(lowerCamelCase ) __snake_case : Optional[Any] = pipe(**lowerCamelCase ).images __snake_case : Any = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) __snake_case : Optional[int] = np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06] ) assert np.abs(image_slice - expected_slice ).max() < 7E-3
203
1
import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) # pylint: disable=invalid-name class __UpperCamelCase ( A__ ): def __init__( self , _UpperCamelCase , _UpperCamelCase=768 ): super().__init__(_UpperCamelCase ) _UpperCAmelCase = proj_size _UpperCAmelCase = CLIPVisionModel(_UpperCamelCase ) _UpperCAmelCase = PaintByExampleMapper(_UpperCamelCase ) _UpperCAmelCase = nn.LayerNorm(config.hidden_size ) _UpperCAmelCase = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling _UpperCAmelCase = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def UpperCamelCase( self , _UpperCamelCase , _UpperCamelCase=False ): _UpperCAmelCase = self.model(pixel_values=_UpperCamelCase ) _UpperCAmelCase = clip_output.pooler_output _UpperCAmelCase = self.mapper(latent_states[:, None] ) _UpperCAmelCase = self.final_layer_norm(_UpperCamelCase ) _UpperCAmelCase = self.proj_out(_UpperCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class __UpperCamelCase ( nn.Module ): def __init__( self , _UpperCamelCase ): super().__init__() _UpperCAmelCase = (config.num_hidden_layers + 1) // 5 _UpperCAmelCase = config.hidden_size _UpperCAmelCase = 1 _UpperCAmelCase = nn.ModuleList( [ BasicTransformerBlock(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , activation_fn='''gelu''' , attention_bias=_UpperCamelCase ) for _ in range(_UpperCamelCase ) ] ) def UpperCamelCase( self , _UpperCamelCase ): for block in self.blocks: _UpperCAmelCase = block(_UpperCamelCase ) return hidden_states
32
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = OrderedDict( [ # Base model mapping ("albert", "FlaxAlbertModel"), ("bart", "FlaxBartModel"), ("beit", "FlaxBeitModel"), ("bert", "FlaxBertModel"), ("big_bird", "FlaxBigBirdModel"), ("blenderbot", "FlaxBlenderbotModel"), ("blenderbot-small", "FlaxBlenderbotSmallModel"), ("clip", "FlaxCLIPModel"), ("distilbert", "FlaxDistilBertModel"), ("electra", "FlaxElectraModel"), ("gpt-sw3", "FlaxGPT2Model"), ("gpt2", "FlaxGPT2Model"), ("gpt_neo", "FlaxGPTNeoModel"), ("gptj", "FlaxGPTJModel"), ("longt5", "FlaxLongT5Model"), ("marian", "FlaxMarianModel"), ("mbart", "FlaxMBartModel"), ("mt5", "FlaxMT5Model"), ("opt", "FlaxOPTModel"), ("pegasus", "FlaxPegasusModel"), ("regnet", "FlaxRegNetModel"), ("resnet", "FlaxResNetModel"), ("roberta", "FlaxRobertaModel"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormModel"), ("roformer", "FlaxRoFormerModel"), ("t5", "FlaxT5Model"), ("vision-text-dual-encoder", "FlaxVisionTextDualEncoderModel"), ("vit", "FlaxViTModel"), ("wav2vec2", "FlaxWav2Vec2Model"), ("whisper", "FlaxWhisperModel"), ("xglm", "FlaxXGLMModel"), ("xlm-roberta", "FlaxXLMRobertaModel"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for pre-training mapping ("albert", "FlaxAlbertForPreTraining"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForPreTraining"), ("big_bird", "FlaxBigBirdForPreTraining"), ("electra", "FlaxElectraForPreTraining"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("t5", "FlaxT5ForConditionalGeneration"), ("wav2vec2", "FlaxWav2Vec2ForPreTraining"), ("whisper", "FlaxWhisperForConditionalGeneration"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Masked LM mapping ("albert", "FlaxAlbertForMaskedLM"), ("bart", "FlaxBartForConditionalGeneration"), ("bert", "FlaxBertForMaskedLM"), ("big_bird", "FlaxBigBirdForMaskedLM"), ("distilbert", "FlaxDistilBertForMaskedLM"), ("electra", "FlaxElectraForMaskedLM"), ("mbart", "FlaxMBartForConditionalGeneration"), ("roberta", "FlaxRobertaForMaskedLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMaskedLM"), ("roformer", "FlaxRoFormerForMaskedLM"), ("xlm-roberta", "FlaxXLMRobertaForMaskedLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ("bart", "FlaxBartForConditionalGeneration"), ("blenderbot", "FlaxBlenderbotForConditionalGeneration"), ("blenderbot-small", "FlaxBlenderbotSmallForConditionalGeneration"), ("encoder-decoder", "FlaxEncoderDecoderModel"), ("longt5", "FlaxLongT5ForConditionalGeneration"), ("marian", "FlaxMarianMTModel"), ("mbart", "FlaxMBartForConditionalGeneration"), ("mt5", "FlaxMT5ForConditionalGeneration"), ("pegasus", "FlaxPegasusForConditionalGeneration"), ("t5", "FlaxT5ForConditionalGeneration"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Image-classsification ("beit", "FlaxBeitForImageClassification"), ("regnet", "FlaxRegNetForImageClassification"), ("resnet", "FlaxResNetForImageClassification"), ("vit", "FlaxViTForImageClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ ("vision-encoder-decoder", "FlaxVisionEncoderDecoderModel"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Causal LM mapping ("bart", "FlaxBartForCausalLM"), ("bert", "FlaxBertForCausalLM"), ("big_bird", "FlaxBigBirdForCausalLM"), ("electra", "FlaxElectraForCausalLM"), ("gpt-sw3", "FlaxGPT2LMHeadModel"), ("gpt2", "FlaxGPT2LMHeadModel"), ("gpt_neo", "FlaxGPTNeoForCausalLM"), ("gptj", "FlaxGPTJForCausalLM"), ("opt", "FlaxOPTForCausalLM"), ("roberta", "FlaxRobertaForCausalLM"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForCausalLM"), ("xglm", "FlaxXGLMForCausalLM"), ("xlm-roberta", "FlaxXLMRobertaForCausalLM"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Sequence Classification mapping ("albert", "FlaxAlbertForSequenceClassification"), ("bart", "FlaxBartForSequenceClassification"), ("bert", "FlaxBertForSequenceClassification"), ("big_bird", "FlaxBigBirdForSequenceClassification"), ("distilbert", "FlaxDistilBertForSequenceClassification"), ("electra", "FlaxElectraForSequenceClassification"), ("mbart", "FlaxMBartForSequenceClassification"), ("roberta", "FlaxRobertaForSequenceClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForSequenceClassification"), ("roformer", "FlaxRoFormerForSequenceClassification"), ("xlm-roberta", "FlaxXLMRobertaForSequenceClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Question Answering mapping ("albert", "FlaxAlbertForQuestionAnswering"), ("bart", "FlaxBartForQuestionAnswering"), ("bert", "FlaxBertForQuestionAnswering"), ("big_bird", "FlaxBigBirdForQuestionAnswering"), ("distilbert", "FlaxDistilBertForQuestionAnswering"), ("electra", "FlaxElectraForQuestionAnswering"), ("mbart", "FlaxMBartForQuestionAnswering"), ("roberta", "FlaxRobertaForQuestionAnswering"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForQuestionAnswering"), ("roformer", "FlaxRoFormerForQuestionAnswering"), ("xlm-roberta", "FlaxXLMRobertaForQuestionAnswering"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Token Classification mapping ("albert", "FlaxAlbertForTokenClassification"), ("bert", "FlaxBertForTokenClassification"), ("big_bird", "FlaxBigBirdForTokenClassification"), ("distilbert", "FlaxDistilBertForTokenClassification"), ("electra", "FlaxElectraForTokenClassification"), ("roberta", "FlaxRobertaForTokenClassification"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForTokenClassification"), ("roformer", "FlaxRoFormerForTokenClassification"), ("xlm-roberta", "FlaxXLMRobertaForTokenClassification"), ] ) UpperCAmelCase_ = OrderedDict( [ # Model for Multiple Choice mapping ("albert", "FlaxAlbertForMultipleChoice"), ("bert", "FlaxBertForMultipleChoice"), ("big_bird", "FlaxBigBirdForMultipleChoice"), ("distilbert", "FlaxDistilBertForMultipleChoice"), ("electra", "FlaxElectraForMultipleChoice"), ("roberta", "FlaxRobertaForMultipleChoice"), ("roberta-prelayernorm", "FlaxRobertaPreLayerNormForMultipleChoice"), ("roformer", "FlaxRoFormerForMultipleChoice"), ("xlm-roberta", "FlaxXLMRobertaForMultipleChoice"), ] ) UpperCAmelCase_ = OrderedDict( [ ("bert", "FlaxBertForNextSentencePrediction"), ] ) UpperCAmelCase_ = OrderedDict( [ ("speech-encoder-decoder", "FlaxSpeechEncoderDecoderModel"), ("whisper", "FlaxWhisperForConditionalGeneration"), ] ) UpperCAmelCase_ = OrderedDict( [ ("whisper", "FlaxWhisperForAudioClassification"), ] ) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) UpperCAmelCase_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModel) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Optional[Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[Any] = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_FOR_MASKED_LM_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : List[str] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Union[str, Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Union[str, Any] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class __UpperCamelCase ( _BaseAutoModelClass ): __A : Any = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class __UpperCamelCase ( _BaseAutoModelClass ): __A : Optional[int] = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING UpperCAmelCase_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="vision-to-text modeling") class __UpperCamelCase ( _BaseAutoModelClass ): __A : str = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING UpperCAmelCase_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc="sequence-to-sequence speech-to-text modeling" )
32
1
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase ): UpperCAmelCase = '''ClapFeatureExtractor''' UpperCAmelCase = ('''RobertaTokenizer''', '''RobertaTokenizerFast''') def __init__( self :Tuple ,__UpperCAmelCase :Optional[Any] ,__UpperCAmelCase :Optional[int] ) -> Any: """simple docstring""" super().__init__(__UpperCAmelCase ,__UpperCAmelCase ) def __call__( self :Dict ,__UpperCAmelCase :str=None ,__UpperCAmelCase :Union[str, Any]=None ,__UpperCAmelCase :Optional[int]=None ,**__UpperCAmelCase :int ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__ : Union[str, Any] = kwargs.pop('''sampling_rate''' ,__UpperCAmelCase ) if text is None and audios is None: raise ValueError('''You have to specify either text or audios. Both cannot be none.''' ) if text is not None: lowerCamelCase__ : List[str] = self.tokenizer(__UpperCAmelCase ,return_tensors=__UpperCAmelCase ,**__UpperCAmelCase ) if audios is not None: lowerCamelCase__ : Union[str, Any] = self.feature_extractor( __UpperCAmelCase ,sampling_rate=__UpperCAmelCase ,return_tensors=__UpperCAmelCase ,**__UpperCAmelCase ) if text is not None and audios is not None: lowerCamelCase__ : Optional[Any] = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**__UpperCAmelCase ) ,tensor_type=__UpperCAmelCase ) def lowercase_ ( self :Dict ,*__UpperCAmelCase :Optional[Any] ,**__UpperCAmelCase :str ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__UpperCAmelCase ,**__UpperCAmelCase ) def lowercase_ ( self :Dict ,*__UpperCAmelCase :str ,**__UpperCAmelCase :int ) -> int: """simple docstring""" return self.tokenizer.decode(*__UpperCAmelCase ,**__UpperCAmelCase ) @property def lowercase_ ( self :Dict ) -> Dict: """simple docstring""" lowerCamelCase__ : str = self.tokenizer.model_input_names lowerCamelCase__ : List[str] = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
121
"""simple docstring""" 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 : def __init__( self :Tuple ,__UpperCAmelCase :str ,__UpperCAmelCase :Tuple=3 ,__UpperCAmelCase :Optional[int]=32 ,__UpperCAmelCase :Optional[int]=3 ,__UpperCAmelCase :Any=10 ,__UpperCAmelCase :str=[8, 16, 32, 64] ,__UpperCAmelCase :str=[1, 1, 2, 1] ,__UpperCAmelCase :List[Any]=True ,__UpperCAmelCase :List[Any]=True ,__UpperCAmelCase :Optional[Any]="relu" ,__UpperCAmelCase :Any=3 ,__UpperCAmelCase :str=None ,__UpperCAmelCase :Union[str, Any]=["stage2", "stage3", "stage4"] ,__UpperCAmelCase :Union[str, Any]=[2, 3, 4] ,__UpperCAmelCase :Union[str, Any]=1 ,) -> List[str]: """simple docstring""" lowerCamelCase__ : List[str] = parent lowerCamelCase__ : List[Any] = batch_size lowerCamelCase__ : Optional[int] = image_size lowerCamelCase__ : Any = num_channels lowerCamelCase__ : Any = embeddings_size lowerCamelCase__ : Tuple = hidden_sizes lowerCamelCase__ : Optional[int] = depths lowerCamelCase__ : List[str] = is_training lowerCamelCase__ : Tuple = use_labels lowerCamelCase__ : Dict = hidden_act lowerCamelCase__ : List[str] = num_labels lowerCamelCase__ : Tuple = scope lowerCamelCase__ : List[Any] = len(__UpperCAmelCase ) lowerCamelCase__ : Optional[Any] = out_features lowerCamelCase__ : List[str] = out_indices lowerCamelCase__ : List[Any] = num_groups def lowercase_ ( self :Optional[Any] ) -> Tuple: """simple docstring""" lowerCamelCase__ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : Optional[Any] = None if self.use_labels: lowerCamelCase__ : Dict = ids_tensor([self.batch_size] ,self.num_labels ) lowerCamelCase__ : List[str] = self.get_config() return config, pixel_values, labels def lowercase_ ( self :str ) -> Any: """simple docstring""" 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 lowercase_ ( self :List[Any] ,__UpperCAmelCase :Optional[int] ,__UpperCAmelCase :Tuple ,__UpperCAmelCase :Tuple ) -> List[Any]: """simple docstring""" lowerCamelCase__ : str = BitModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCamelCase__ : Optional[Any] = model(__UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def lowercase_ ( self :int ,__UpperCAmelCase :int ,__UpperCAmelCase :int ,__UpperCAmelCase :Optional[int] ) -> Optional[int]: """simple docstring""" lowerCamelCase__ : List[Any] = self.num_labels lowerCamelCase__ : Union[str, Any] = BitForImageClassification(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCamelCase__ : str = model(__UpperCAmelCase ,labels=__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def lowercase_ ( self :Any ,__UpperCAmelCase :Dict ,__UpperCAmelCase :Optional[int] ,__UpperCAmelCase :str ) -> str: """simple docstring""" lowerCamelCase__ : int = BitBackbone(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCamelCase__ : List[str] = model(__UpperCAmelCase ) # 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 lowerCamelCase__ : str = None lowerCamelCase__ : Optional[int] = BitBackbone(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() lowerCamelCase__ : List[Any] = model(__UpperCAmelCase ) # 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 lowercase_ ( self :int ) -> Optional[int]: """simple docstring""" lowerCamelCase__ : Optional[int] = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ : str = config_and_inputs lowerCamelCase__ : Union[str, Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): UpperCAmelCase = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () UpperCAmelCase = ( {'''feature-extraction''': BitModel, '''image-classification''': BitForImageClassification} if is_torch_available() else {} ) UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False UpperCAmelCase = False def lowercase_ ( self :List[str] ) -> Any: """simple docstring""" lowerCamelCase__ : Any = BitModelTester(self ) lowerCamelCase__ : Any = ConfigTester(self ,config_class=__UpperCAmelCase ,has_text_modality=__UpperCAmelCase ) def lowercase_ ( self :Optional[Any] ) -> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def lowercase_ ( self :List[Any] ) -> Dict: """simple docstring""" return @unittest.skip(reason='''Bit does not output attentions''' ) def lowercase_ ( self :List[Any] ) -> str: """simple docstring""" pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def lowercase_ ( self :List[Any] ) -> Optional[int]: """simple docstring""" pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def lowercase_ ( self :Tuple ) -> List[Any]: """simple docstring""" pass def lowercase_ ( self :Optional[Any] ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Optional[int] = model_class(__UpperCAmelCase ) lowerCamelCase__ : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : int = [*signature.parameters.keys()] lowerCamelCase__ : Tuple = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,__UpperCAmelCase ) def lowercase_ ( self :str ) -> List[str]: """simple docstring""" lowerCamelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__UpperCAmelCase ) def lowercase_ ( self :Optional[int] ) -> Union[str, Any]: """simple docstring""" lowerCamelCase__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*__UpperCAmelCase ) def lowercase_ ( self :List[str] ) -> List[str]: """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Any = model_class(config=__UpperCAmelCase ) for name, module in model.named_modules(): if isinstance(__UpperCAmelCase ,(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 lowercase_ ( self :List[str] ) -> Dict: """simple docstring""" def check_hidden_states_output(__UpperCAmelCase :Tuple ,__UpperCAmelCase :str ,__UpperCAmelCase :Tuple ): lowerCamelCase__ : List[str] = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() with torch.no_grad(): lowerCamelCase__ : Optional[Any] = model(**self._prepare_for_class(__UpperCAmelCase ,__UpperCAmelCase ) ) lowerCamelCase__ : Optional[int] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states lowerCamelCase__ : Union[str, Any] = self.model_tester.num_stages self.assertEqual(len(__UpperCAmelCase ) ,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] ,) lowerCamelCase__ , lowerCamelCase__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowerCamelCase__ : Any = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: lowerCamelCase__ : List[Any] = layer_type lowerCamelCase__ : Tuple = True check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ : Optional[Any] = True check_hidden_states_output(__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def lowercase_ ( self :Optional[int] ) -> Optional[int]: """simple docstring""" pass def lowercase_ ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" lowerCamelCase__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase ) @slow def lowercase_ ( self :Union[str, Any] ) -> Optional[Any]: """simple docstring""" for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Optional[int] = BitModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def __a ( ): """simple docstring""" lowerCamelCase__ : Dict = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): @cached_property def lowercase_ ( self :Tuple ) -> Dict: """simple docstring""" return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowercase_ ( self :List[Any] ) -> int: """simple docstring""" lowerCamelCase__ : Optional[int] = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__UpperCAmelCase ) lowerCamelCase__ : Any = self.default_image_processor lowerCamelCase__ : Optional[int] = prepare_img() lowerCamelCase__ : List[Any] = image_processor(images=__UpperCAmelCase ,return_tensors='''pt''' ).to(__UpperCAmelCase ) # forward pass with torch.no_grad(): lowerCamelCase__ : Union[str, Any] = model(**__UpperCAmelCase ) # verify the logits lowerCamelCase__ : int = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape ,__UpperCAmelCase ) lowerCamelCase__ : int = torch.tensor([[-0.6_526, -0.5_263, -1.4_398]] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,__UpperCAmelCase ,atol=1E-4 ) ) @require_torch class __SCREAMING_SNAKE_CASE ( _lowerCAmelCase , unittest.TestCase ): UpperCAmelCase = (BitBackbone,) if is_torch_available() else () UpperCAmelCase = BitConfig UpperCAmelCase = False def lowercase_ ( self :List[str] ) -> int: """simple docstring""" lowerCamelCase__ : Any = BitModelTester(self )
121
1
'''simple docstring''' def a ( lowerCamelCase__ = 1_00_00_00 ): '''simple docstring''' A_ : Optional[Any] = set(range(3 , _lowercase , 2 ) ) primes.add(2 ) for p in range(3 , _lowercase , 2 ): if p not in primes: continue primes.difference_update(set(range(p * p , _lowercase , _lowercase ) ) ) A_ : Dict = [float(_lowercase ) for n in range(limit + 1 )] for p in primes: for n in range(_lowercase , limit + 1 , _lowercase ): phi[n] *= 1 - 1 / p return int(sum(phi[2:] ) ) if __name__ == "__main__": print(F"{solution() = }")
667
"""simple docstring""" import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def __snake_case ( ): """simple docstring""" raise RuntimeError('''CUDA out of memory.''' ) class snake_case_ ( nn.Module ): """simple docstring""" def __init__( self) -> Any: super().__init__() UpperCamelCase = nn.Linear(3 , 4) UpperCamelCase = nn.BatchNormad(4) UpperCamelCase = nn.Linear(4 , 5) def UpperCAmelCase__ ( self , lowerCamelCase_) -> Union[str, Any]: return self.lineara(self.batchnorm(self.lineara(lowerCamelCase_))) class snake_case_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self) -> List[Any]: UpperCamelCase = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(lowerCamelCase_): nonlocal batch_sizes batch_sizes.append(lowerCamelCase_) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(lowerCamelCase_ , [1_2_8, 6_4, 3_2, 1_6, 8]) def UpperCAmelCase__ ( self) -> Optional[Any]: UpperCamelCase = [] @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(lowerCamelCase_ , lowerCamelCase_): nonlocal batch_sizes batch_sizes.append(lowerCamelCase_) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga UpperCamelCase , UpperCamelCase = mock_training_loop_function('''hello''') self.assertListEqual(lowerCamelCase_ , [1_2_8, 6_4, 3_2, 1_6, 8]) self.assertListEqual([bs, arga] , [8, '''hello''']) def UpperCAmelCase__ ( self) -> Tuple: @find_executable_batch_size(starting_batch_size=0) def mock_training_loop_function(lowerCamelCase_): pass with self.assertRaises(lowerCamelCase_) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0]) def UpperCAmelCase__ ( self) -> List[Any]: @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(lowerCamelCase_): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(lowerCamelCase_) as cm: mock_training_loop_function() self.assertIn('''No executable batch size found, reached zero.''' , cm.exception.args[0]) def UpperCAmelCase__ ( self) -> Union[str, Any]: @find_executable_batch_size(starting_batch_size=1_2_8) def mock_training_loop_function(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(lowerCamelCase_) as cm: mock_training_loop_function(1_2_8 , '''hello''' , '''world''') self.assertIn('''Batch size was passed into `f`''' , cm.exception.args[0]) self.assertIn('''`f(arg1=\'hello\', arg2=\'world\')''' , cm.exception.args[0]) def UpperCAmelCase__ ( self) -> Dict: @find_executable_batch_size(starting_batch_size=1_6) def mock_training_loop_function(lowerCamelCase_): raise ValueError('''Oops, we had an error!''') with self.assertRaises(lowerCamelCase_) as cm: mock_training_loop_function() self.assertIn('''Oops, we had an error!''' , cm.exception.args[0]) @require_cuda def UpperCAmelCase__ ( self) -> Optional[int]: UpperCamelCase = torch.cuda.memory_allocated() UpperCamelCase = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , lowerCamelCase_) UpperCamelCase = release_memory(lowerCamelCase_) self.assertEqual(torch.cuda.memory_allocated() , lowerCamelCase_)
34
0
"""simple docstring""" from argparse import ArgumentParser, Namespace from typing import Any, List, Optional from ..pipelines import Pipeline, get_supported_tasks, pipeline from ..utils import logging from . import BaseTransformersCLICommand try: from fastapi import Body, FastAPI, HTTPException from fastapi.routing import APIRoute from pydantic import BaseModel from starlette.responses import JSONResponse from uvicorn import run a_ = True except (ImportError, AttributeError): a_ = object def UpperCAmelCase_ ( *__a : Dict , **__a : Optional[int] ): '''simple docstring''' pass a_ = False a_ = logging.get_logger("""transformers-cli/serving""") def UpperCAmelCase_ ( __a : Namespace ): '''simple docstring''' _lowerCamelCase : Optional[Any] = pipeline( task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , ) return ServeCommand(__a , args.host , args.port , args.workers ) class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : dict class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : List[str] a_ : Optional[List[int]] class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : str class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : Any class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" @staticmethod def _lowerCAmelCase ( A ): _lowerCamelCase : List[str] = parser.add_parser( 'serve' , help='CLI tool to run inference requests through REST and GraphQL endpoints.' ) serve_parser.add_argument( '--task' , type=A , choices=get_supported_tasks() , help='The task to run the pipeline on' , ) serve_parser.add_argument('--host' , type=A , default='localhost' , help='Interface the server will listen on.' ) serve_parser.add_argument('--port' , type=A , default=8888 , help='Port the serving will listen to.' ) serve_parser.add_argument('--workers' , type=A , default=1 , help='Number of http workers' ) serve_parser.add_argument('--model' , type=A , help='Model\'s name or path to stored model.' ) serve_parser.add_argument('--config' , type=A , help='Model\'s config name or path to stored model.' ) serve_parser.add_argument('--tokenizer' , type=A , help='Tokenizer name to use.' ) serve_parser.add_argument( '--device' , type=A , default=-1 , help='Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)' , ) serve_parser.set_defaults(func=A ) def __init__( self , A , A , A , A ): _lowerCamelCase : Tuple = pipeline _lowerCamelCase : Union[str, Any] = host _lowerCamelCase : Any = port _lowerCamelCase : int = workers if not _serve_dependencies_installed: raise RuntimeError( 'Using serve command requires FastAPI and uvicorn. ' 'Please install transformers with [serving]: pip install "transformers[serving]".' 'Or install FastAPI and uvicorn separately.' ) else: logger.info(F"Serving model over {host}:{port}" ) _lowerCamelCase : Dict = FastAPI( routes=[ APIRoute( '/' , self.model_info , response_model=A , response_class=A , methods=['GET'] , ), APIRoute( '/tokenize' , self.tokenize , response_model=A , response_class=A , methods=['POST'] , ), APIRoute( '/detokenize' , self.detokenize , response_model=A , response_class=A , methods=['POST'] , ), APIRoute( '/forward' , self.forward , response_model=A , response_class=A , methods=['POST'] , ), ] , timeout=600 , ) def _lowerCAmelCase ( self ): run(self._app , host=self.host , port=self.port , workers=self.workers ) def _lowerCAmelCase ( self ): return ServeModelInfoResult(infos=vars(self._pipeline.model.config ) ) def _lowerCAmelCase ( self , A = Body(A , embed=A ) , A = Body(A , embed=A ) ): try: _lowerCamelCase : List[Any] = self._pipeline.tokenizer.tokenize(A ) if return_ids: _lowerCamelCase : Dict = self._pipeline.tokenizer.convert_tokens_to_ids(A ) return ServeTokenizeResult(tokens=A , tokens_ids=A ) else: return ServeTokenizeResult(tokens=A ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(A )} ) def _lowerCAmelCase ( self , A = Body(A , embed=A ) , A = Body(A , embed=A ) , A = Body(A , embed=A ) , ): try: _lowerCamelCase : List[str] = self._pipeline.tokenizer.decode(A , A , A ) return ServeDeTokenizeResult(model='' , text=A ) except Exception as e: raise HTTPException(status_code=500 , detail={'model': '', 'error': str(A )} ) async def _lowerCAmelCase ( self , A=Body(A , embed=A ) ): # Check we don't have empty string if len(A ) == 0: return ServeForwardResult(output=[] , attention=[] ) try: # Forward through the model _lowerCamelCase : int = self._pipeline(A ) return ServeForwardResult(output=A ) except Exception as e: raise HTTPException(500 , {'error': str(A )} )
349
"""simple docstring""" import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 a_ = sys.version_info >= (3, 10) def UpperCAmelCase_ ( __a : List[str]=None , __a : List[str]=None ): '''simple docstring''' return field(default_factory=lambda: default , metadata=__a ) @dataclass class A_: """simple docstring""" a_ : int a_ : float a_ : str a_ : bool @dataclass class A_: """simple docstring""" a_ : int = 42 a_ : str = field(default="""toto""" , metadata={"""help""": """help message"""} ) @dataclass class A_: """simple docstring""" a_ : bool = False a_ : bool = True a_ : Optional[bool] = None class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : Tuple = """titi""" a_ : Tuple = """toto""" class A_(SCREAMING_SNAKE_CASE_ ): """simple docstring""" a_ : str = """titi""" a_ : Union[str, Any] = """toto""" a_ : Union[str, Any] = 42 @dataclass class A_: """simple docstring""" a_ : BasicEnum = "toto" def _lowerCAmelCase ( self ): _lowerCamelCase : Tuple = BasicEnum(self.foo ) @dataclass class A_: """simple docstring""" a_ : MixedTypeEnum = "toto" def _lowerCAmelCase ( self ): _lowerCamelCase : Tuple = MixedTypeEnum(self.foo ) @dataclass class A_: """simple docstring""" a_ : Optional[int] = None a_ : Optional[float] = field(default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """help message"""} ) a_ : Optional[str] = None a_ : Optional[List[str]] = list_field(default=[] ) a_ : Optional[List[int]] = list_field(default=[] ) @dataclass class A_: """simple docstring""" a_ : List[int] = list_field(default=[] ) a_ : List[int] = list_field(default=[1, 2, 3] ) a_ : List[str] = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) a_ : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class A_: """simple docstring""" a_ : List[int] = field() a_ : str = field() a_ : BasicEnum = field() def _lowerCAmelCase ( self ): _lowerCamelCase : List[str] = BasicEnum(self.required_enum ) @dataclass class A_: """simple docstring""" a_ : int a_ : "BasicEnum" = field() a_ : "Optional[bool]" = None a_ : "str" = field(default="""toto""" , metadata={"""help""": """help message"""} ) a_ : "List[str]" = list_field(default=["""Hallo""", """Bonjour""", """Hello"""] ) if is_python_no_less_than_3_10: @dataclass class A_: """simple docstring""" a_ : bool = False a_ : bool = True a_ : bool | None = None @dataclass class A_: """simple docstring""" a_ : int | None = None a_ : float | None = field(default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """help message"""} ) a_ : str | None = None a_ : list[str] | None = list_field(default=[] ) a_ : list[int] | None = list_field(default=[] ) class A_(unittest.TestCase ): """simple docstring""" def _lowerCAmelCase ( self , A , A ): self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): _lowerCamelCase : Dict = {k: v for k, v in vars(A ).items() if k != 'container'} _lowerCamelCase : Optional[Any] = {k: v for k, v in vars(A ).items() if k != 'container'} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get('choices' , A ) and yy.get('choices' , A ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx['type'](A ) , yy['type'](A ) ) del xx["type"], yy["type"] self.assertEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : List[Any] = HfArgumentParser(A ) _lowerCamelCase : Any = argparse.ArgumentParser() expected.add_argument('--foo' , type=A , required=A ) expected.add_argument('--bar' , type=A , required=A ) expected.add_argument('--baz' , type=A , required=A ) expected.add_argument('--flag' , type=A , default=A , const=A , nargs='?' ) self.argparsersEqual(A , A ) _lowerCamelCase : Optional[Any] = ['--foo', '1', '--baz', 'quux', '--bar', '0.5'] ((_lowerCamelCase) , ) : str = parser.parse_args_into_dataclasses(A , look_for_args_file=A ) self.assertFalse(example.flag ) def _lowerCAmelCase ( self ): _lowerCamelCase : List[str] = HfArgumentParser(A ) _lowerCamelCase : int = argparse.ArgumentParser() expected.add_argument('--foo' , default=42 , type=A ) expected.add_argument('--baz' , default='toto' , type=A , help='help message' ) self.argparsersEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : Union[str, Any] = argparse.ArgumentParser() expected.add_argument('--foo' , type=A , default=A , const=A , nargs='?' ) expected.add_argument('--baz' , type=A , default=A , const=A , nargs='?' ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument('--no_baz' , action='store_false' , default=A , dest='baz' ) expected.add_argument('--opt' , type=A , default=A ) _lowerCamelCase : Optional[Any] = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(A ) for dataclass_type in dataclass_types: _lowerCamelCase : List[Any] = HfArgumentParser(A ) self.argparsersEqual(A , A ) _lowerCamelCase : Union[str, Any] = parser.parse_args([] ) self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) ) _lowerCamelCase : List[Any] = parser.parse_args(['--foo', '--no_baz'] ) self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) ) _lowerCamelCase : Union[str, Any] = parser.parse_args(['--foo', '--baz'] ) self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) ) _lowerCamelCase : Dict = parser.parse_args(['--foo', 'True', '--baz', 'True', '--opt', 'True'] ) self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) ) _lowerCamelCase : Any = parser.parse_args(['--foo', 'False', '--baz', 'False', '--opt', 'False'] ) self.assertEqual(A , Namespace(foo=A , baz=A , opt=A ) ) def _lowerCAmelCase ( self ): _lowerCamelCase : Optional[int] = HfArgumentParser(A ) _lowerCamelCase : Tuple = argparse.ArgumentParser() expected.add_argument( '--foo' , default='toto' , choices=['titi', 'toto', 42] , type=make_choice_type_function(['titi', 'toto', 42] ) , ) self.argparsersEqual(A , A ) _lowerCamelCase : Optional[int] = parser.parse_args([] ) self.assertEqual(args.foo , 'toto' ) _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) _lowerCamelCase : List[Any] = parser.parse_args(['--foo', 'titi'] ) self.assertEqual(args.foo , 'titi' ) _lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses(['--foo', 'titi'] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) _lowerCamelCase : Dict = parser.parse_args(['--foo', '42'] ) self.assertEqual(args.foo , 42 ) _lowerCamelCase : List[Any] = parser.parse_args_into_dataclasses(['--foo', '42'] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def _lowerCAmelCase ( self ): @dataclass class A_: """simple docstring""" a_ : Literal["titi", "toto", 42] = "toto" _lowerCamelCase : Optional[int] = HfArgumentParser(A ) _lowerCamelCase : str = argparse.ArgumentParser() expected.add_argument( '--foo' , default='toto' , choices=('titi', 'toto', 42) , type=make_choice_type_function(['titi', 'toto', 42] ) , ) self.argparsersEqual(A , A ) _lowerCamelCase : Union[str, Any] = parser.parse_args([] ) self.assertEqual(args.foo , 'toto' ) _lowerCamelCase : List[Any] = parser.parse_args(['--foo', 'titi'] ) self.assertEqual(args.foo , 'titi' ) _lowerCamelCase : Dict = parser.parse_args(['--foo', '42'] ) self.assertEqual(args.foo , 42 ) def _lowerCAmelCase ( self ): _lowerCamelCase : Tuple = HfArgumentParser(A ) _lowerCamelCase : int = argparse.ArgumentParser() expected.add_argument('--foo_int' , nargs='+' , default=[] , type=A ) expected.add_argument('--bar_int' , nargs='+' , default=[1, 2, 3] , type=A ) expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=A ) expected.add_argument('--foo_float' , nargs='+' , default=[0.1, 0.2, 0.3] , type=A ) self.argparsersEqual(A , A ) _lowerCamelCase : List[str] = parser.parse_args([] ) self.assertEqual( A , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=['Hallo', 'Bonjour', 'Hello'] , foo_float=[0.1, 0.2, 0.3] ) , ) _lowerCamelCase : Optional[int] = parser.parse_args('--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'.split() ) self.assertEqual(A , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=['a', 'b', 'c'] , foo_float=[0.1, 0.7] ) ) def _lowerCAmelCase ( self ): _lowerCamelCase : Tuple = argparse.ArgumentParser() expected.add_argument('--foo' , default=A , type=A ) expected.add_argument('--bar' , default=A , type=A , help='help message' ) expected.add_argument('--baz' , default=A , type=A ) expected.add_argument('--ces' , nargs='+' , default=[] , type=A ) expected.add_argument('--des' , nargs='+' , default=[] , type=A ) _lowerCamelCase : Any = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(A ) for dataclass_type in dataclass_types: _lowerCamelCase : Optional[Any] = HfArgumentParser(A ) self.argparsersEqual(A , A ) _lowerCamelCase : List[Any] = parser.parse_args([] ) self.assertEqual(A , Namespace(foo=A , bar=A , baz=A , ces=[] , des=[] ) ) _lowerCamelCase : Union[str, Any] = parser.parse_args('--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'.split() ) self.assertEqual(A , Namespace(foo=12 , bar=3.1_4 , baz='42' , ces=['a', 'b', 'c'] , des=[1, 2, 3] ) ) def _lowerCAmelCase ( self ): _lowerCamelCase : Union[str, Any] = HfArgumentParser(A ) _lowerCamelCase : Tuple = argparse.ArgumentParser() expected.add_argument('--required_list' , nargs='+' , type=A , required=A ) expected.add_argument('--required_str' , type=A , required=A ) expected.add_argument( '--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=A , ) self.argparsersEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : Optional[int] = HfArgumentParser(A ) _lowerCamelCase : List[str] = argparse.ArgumentParser() expected.add_argument('--foo' , type=A , required=A ) expected.add_argument( '--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=A , ) expected.add_argument('--opt' , type=A , default=A ) expected.add_argument('--baz' , default='toto' , type=A , help='help message' ) expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=A ) self.argparsersEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : List[str] = HfArgumentParser(A ) _lowerCamelCase : str = { 'foo': 12, 'bar': 3.1_4, 'baz': '42', 'flag': True, } _lowerCamelCase : Any = parser.parse_dict(A )[0] _lowerCamelCase : Any = BasicExample(**A ) self.assertEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : int = HfArgumentParser(A ) _lowerCamelCase : Optional[Any] = { 'foo': 12, 'bar': 3.1_4, 'baz': '42', 'flag': True, 'extra': 42, } self.assertRaises(A , parser.parse_dict , A , allow_extra_keys=A ) def _lowerCAmelCase ( self ): _lowerCamelCase : Dict = HfArgumentParser(A ) _lowerCamelCase : Tuple = { 'foo': 12, 'bar': 3.1_4, 'baz': '42', 'flag': True, } with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : Union[str, Any] = os.path.join(A , 'temp_json' ) os.mkdir(A ) with open(temp_local_path + '.json' , 'w+' ) as f: json.dump(A , A ) _lowerCamelCase : Optional[Any] = parser.parse_yaml_file(Path(temp_local_path + '.json' ) )[0] _lowerCamelCase : Union[str, Any] = BasicExample(**A ) self.assertEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : Optional[int] = HfArgumentParser(A ) _lowerCamelCase : Dict = { 'foo': 12, 'bar': 3.1_4, 'baz': '42', 'flag': True, } with tempfile.TemporaryDirectory() as tmp_dir: _lowerCamelCase : int = os.path.join(A , 'temp_yaml' ) os.mkdir(A ) with open(temp_local_path + '.yaml' , 'w+' ) as f: yaml.dump(A , A ) _lowerCamelCase : Optional[int] = parser.parse_yaml_file(Path(temp_local_path + '.yaml' ) )[0] _lowerCamelCase : Any = BasicExample(**A ) self.assertEqual(A , A ) def _lowerCAmelCase ( self ): _lowerCamelCase : int = HfArgumentParser(A ) self.assertIsNotNone(A )
349
1
'''simple docstring''' import math def __magic_name__ ( __UpperCAmelCase ) -> str: '''simple docstring''' __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = 0 while num > 0: __SCREAMING_SNAKE_CASE = num % 8 __SCREAMING_SNAKE_CASE = octal + (remainder * math.floor(math.pow(10 , __UpperCAmelCase ) )) counter += 1 __SCREAMING_SNAKE_CASE = math.floor(num / 8 ) # basically /= 8 without remainder if any # This formatting removes trailing '.0' from `octal`. return f"""0o{int(__UpperCAmelCase )}""" def __magic_name__ ( ) -> None: '''simple docstring''' print("""\n2 in octal is:""" ) print(decimal_to_octal(2 ) ) # = 2 print("""\n8 in octal is:""" ) print(decimal_to_octal(8 ) ) # = 10 print("""\n65 in octal is:""" ) print(decimal_to_octal(65 ) ) # = 101 print("""\n216 in octal is:""" ) print(decimal_to_octal(216 ) ) # = 330 print("""\n512 in octal is:""" ) print(decimal_to_octal(512 ) ) # = 1000 print("""\n""" ) if __name__ == "__main__": main()
109
'''simple docstring''' import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel a = { "gwf-440k": { "url": "https://model-server.zqevans2.workers.dev/gwf-440k.ckpt", "sample_rate": 48000, "sample_size": 65536, }, "jmann-small-190k": { "url": "https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt", "sample_rate": 48000, "sample_size": 65536, }, "jmann-large-580k": { "url": "https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt", "sample_rate": 48000, "sample_size": 131072, }, "maestro-uncond-150k": { "url": "https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt", "sample_rate": 16000, "sample_size": 65536, }, "unlocked-uncond-250k": { "url": "https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt", "sample_rate": 16000, "sample_size": 65536, }, "honk-140k": { "url": "https://model-server.zqevans2.workers.dev/honk-140k.ckpt", "sample_rate": 16000, "sample_size": 65536, }, } def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' return torch.atana(__UpperCAmelCase , __UpperCAmelCase ) / math.pi * 2 def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.sin(t * math.pi / 2 ) ** 2 __SCREAMING_SNAKE_CASE = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(__UpperCAmelCase , __UpperCAmelCase ) class __a ( _snake_case ): pass class __a ( nn.Module ): def __init__( self : Union[str, Any] ,lowerCamelCase : Union[str, Any] ): '''simple docstring''' super().__init__() __SCREAMING_SNAKE_CASE = DiffusionAttnUnetaD(lowerCamelCase ,n_attn_layers=4 ) __SCREAMING_SNAKE_CASE = deepcopy(self.diffusion ) __SCREAMING_SNAKE_CASE = torch.quasirandom.SobolEngine(1 ,scramble=lowerCamelCase ) def __magic_name__ ( __UpperCAmelCase ) -> List[str]: '''simple docstring''' __SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""url"""] os.system(f"""wget {url} ./""" ) return f"""./{model_name}.ckpt""" a = { "1": "resnets.0", "2": "attentions.0", "3": "resnets.1", "4": "attentions.1", "5": "resnets.2", "6": "attentions.2", } a = { "8": "resnets.0", "9": "attentions.0", "10": "resnets.1", "11": "attentions.1", "12": "resnets.2", "13": "attentions.2", } a = { "1": "resnets.0", "2": "attentions.0", "3": "resnets.1", "4": "attentions.1", "5": "resnets.2", "6": "attentions.2", "8": "resnets.3", "9": "attentions.3", "10": "resnets.4", "11": "attentions.4", "12": "resnets.5", "13": "attentions.5", } a = { "0": "resnets.0", "1": "resnets.1", "2": "resnets.2", "4": "resnets.0", "5": "resnets.1", "6": "resnets.2", } a = { "skip": "conv_skip", "main.0": "conv_1", "main.1": "group_norm_1", "main.3": "conv_2", "main.4": "group_norm_2", } a = { "norm": "group_norm", "qkv_proj": ["query", "key", "value"], "out_proj": ["proj_attn"], } def __magic_name__ ( __UpperCAmelCase ) -> int: '''simple docstring''' if name.startswith("""skip""" ): return name.replace("""skip""" , RES_CONV_MAP["""skip"""] ) # name has to be of format main.{digit} if not name.startswith("""main.""" ): raise ValueError(f"""ResConvBlock error with {name}""" ) return name.replace(name[:6] , RES_CONV_MAP[name[:6]] ) def __magic_name__ ( __UpperCAmelCase ) -> Union[str, Any]: '''simple docstring''' for key, value in ATTN_MAP.items(): if name.startswith(__UpperCAmelCase ) and not isinstance(__UpperCAmelCase , __UpperCAmelCase ): return name.replace(__UpperCAmelCase , __UpperCAmelCase ) elif name.startswith(__UpperCAmelCase ): return [name.replace(__UpperCAmelCase , __UpperCAmelCase ) for v in value] raise ValueError(f"""Attn error with {name}""" ) def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase=13 ) -> Optional[int]: '''simple docstring''' __SCREAMING_SNAKE_CASE = input_string if string.split(""".""" )[0] == "timestep_embed": return string.replace("""timestep_embed""" , """time_proj""" ) __SCREAMING_SNAKE_CASE = 0 if string.startswith("""net.3.""" ): depth += 1 __SCREAMING_SNAKE_CASE = string[6:] elif string.startswith("""net.""" ): __SCREAMING_SNAKE_CASE = string[4:] while string.startswith("""main.7.""" ): depth += 1 __SCREAMING_SNAKE_CASE = string[7:] if string.startswith("""main.""" ): __SCREAMING_SNAKE_CASE = string[5:] # mid block if string[:2].isdigit(): __SCREAMING_SNAKE_CASE = string[:2] __SCREAMING_SNAKE_CASE = string[2:] else: __SCREAMING_SNAKE_CASE = string[0] __SCREAMING_SNAKE_CASE = string[1:] if depth == max_depth: __SCREAMING_SNAKE_CASE = MID_NUM_TO_LAYER[layer_num] __SCREAMING_SNAKE_CASE = """mid_block""" elif depth > 0 and int(__UpperCAmelCase ) < 7: __SCREAMING_SNAKE_CASE = DOWN_NUM_TO_LAYER[layer_num] __SCREAMING_SNAKE_CASE = f"""down_blocks.{depth}""" elif depth > 0 and int(__UpperCAmelCase ) > 7: __SCREAMING_SNAKE_CASE = UP_NUM_TO_LAYER[layer_num] __SCREAMING_SNAKE_CASE = f"""up_blocks.{max_depth - depth - 1}""" elif depth == 0: __SCREAMING_SNAKE_CASE = DEPTH_0_TO_LAYER[layer_num] __SCREAMING_SNAKE_CASE = f"""up_blocks.{max_depth - 1}""" if int(__UpperCAmelCase ) > 3 else """down_blocks.0""" if not string_left.startswith(""".""" ): raise ValueError(f"""Naming error with {input_string} and string_left: {string_left}.""" ) __SCREAMING_SNAKE_CASE = string_left[1:] if "resnets" in new_layer: __SCREAMING_SNAKE_CASE = convert_resconv_naming(__UpperCAmelCase ) elif "attentions" in new_layer: __SCREAMING_SNAKE_CASE = convert_attn_naming(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = new_string_left if not isinstance(__UpperCAmelCase , __UpperCAmelCase ): __SCREAMING_SNAKE_CASE = prefix + """.""" + new_layer + """.""" + string_left else: __SCREAMING_SNAKE_CASE = [prefix + """.""" + new_layer + """.""" + s for s in string_left] return new_string def __magic_name__ ( __UpperCAmelCase ) -> Optional[int]: '''simple docstring''' __SCREAMING_SNAKE_CASE = {} for k, v in state_dict.items(): if k.endswith("""kernel""" ): # up- and downsample layers, don't have trainable weights continue __SCREAMING_SNAKE_CASE = rename(__UpperCAmelCase ) # check if we need to transform from Conv => Linear for attention if isinstance(__UpperCAmelCase , __UpperCAmelCase ): __SCREAMING_SNAKE_CASE = transform_conv_attns(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) else: __SCREAMING_SNAKE_CASE = v return new_state_dict def __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]: '''simple docstring''' if len(__UpperCAmelCase ) == 1: if len(v.shape ) == 3: # weight __SCREAMING_SNAKE_CASE = v[:, :, 0] else: # bias __SCREAMING_SNAKE_CASE = v else: # qkv matrices __SCREAMING_SNAKE_CASE = v.shape[0] __SCREAMING_SNAKE_CASE = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __SCREAMING_SNAKE_CASE = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __SCREAMING_SNAKE_CASE = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def __magic_name__ ( __UpperCAmelCase ) -> Dict: '''simple docstring''' __SCREAMING_SNAKE_CASE = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) __SCREAMING_SNAKE_CASE = args.model_path.split("""/""" )[-1].split(""".""" )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f"""Make sure to provide one of the official model names {MODELS_MAP.keys()}""" __SCREAMING_SNAKE_CASE = download(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""sample_rate"""] __SCREAMING_SNAKE_CASE = MODELS_MAP[model_name]["""sample_size"""] __SCREAMING_SNAKE_CASE = Object() __SCREAMING_SNAKE_CASE = sample_size __SCREAMING_SNAKE_CASE = sample_rate __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = UNetaDModel(sample_size=__UpperCAmelCase , sample_rate=__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = diffusers_model.state_dict() __SCREAMING_SNAKE_CASE = DiffusionUncond(__UpperCAmelCase ) orig_model.load_state_dict(torch.load(args.model_path , map_location=__UpperCAmelCase )["""state_dict"""] ) __SCREAMING_SNAKE_CASE = orig_model.diffusion_ema.eval() __SCREAMING_SNAKE_CASE = orig_model.state_dict() __SCREAMING_SNAKE_CASE = rename_orig_weights(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __SCREAMING_SNAKE_CASE = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(__UpperCAmelCase ) == 0, f"""Problem with {renamed_minus_diffusers}""" assert all(k.endswith("""kernel""" ) for k in list(__UpperCAmelCase ) ), f"""Problem with {diffusers_minus_renamed}""" for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f"""Shape for {key} doesn't match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}""" if key == "time_proj.weight": __SCREAMING_SNAKE_CASE = value.squeeze() __SCREAMING_SNAKE_CASE = value diffusers_model.load_state_dict(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = 100 __SCREAMING_SNAKE_CASE = 33 __SCREAMING_SNAKE_CASE = IPNDMScheduler(num_train_timesteps=__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = torch.manual_seed(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = torch.randn([1, 2, config.sample_size] , generator=__UpperCAmelCase ).to(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = torch.linspace(1 , 0 , steps + 1 , device=__UpperCAmelCase )[:-1] __SCREAMING_SNAKE_CASE = get_crash_schedule(__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = DanceDiffusionPipeline(unet=__UpperCAmelCase , scheduler=__UpperCAmelCase ) __SCREAMING_SNAKE_CASE = torch.manual_seed(33 ) __SCREAMING_SNAKE_CASE = pipe(num_inference_steps=__UpperCAmelCase , generator=__UpperCAmelCase ).audios __SCREAMING_SNAKE_CASE = sampling.iplms_sample(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {} ) __SCREAMING_SNAKE_CASE = generated.clamp(-1 , 1 ) __SCREAMING_SNAKE_CASE = (generated - audio).abs().sum() __SCREAMING_SNAKE_CASE = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print("""Diff sum""" , __UpperCAmelCase ) print("""Diff max""" , __UpperCAmelCase ) assert diff_max < 1e-3, f"""Diff max: {diff_max} is too much :-/""" print(f"""Conversion for {model_name} successful!""" ) if __name__ == "__main__": a = argparse.ArgumentParser() parser.add_argument("--model_path", default=None, type=str, required=True, help="Path to the model to convert.") parser.add_argument( "--save", default=True, type=bool, required=False, help="Whether to save the converted model or not." ) parser.add_argument("--checkpoint_path", default=None, type=str, required=True, help="Path to the output model.") a = parser.parse_args() main(args)
109
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer _UpperCAmelCase = logging.get_logger(__name__) _UpperCAmelCase = {"vocab_file": "vocab.txt"} _UpperCAmelCase = { "vocab_file": { "YituTech/conv-bert-base": "https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt", "YituTech/conv-bert-medium-small": ( "https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt" ), "YituTech/conv-bert-small": "https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt", } } _UpperCAmelCase = { "YituTech/conv-bert-base": 512, "YituTech/conv-bert-medium-small": 512, "YituTech/conv-bert-small": 512, } _UpperCAmelCase = { "YituTech/conv-bert-base": {"do_lower_case": True}, "YituTech/conv-bert-medium-small": {"do_lower_case": True}, "YituTech/conv-bert-small": {"do_lower_case": True}, } class __magic_name__ ( lowercase_ ): """simple docstring""" _UpperCamelCase = VOCAB_FILES_NAMES _UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP _UpperCamelCase = PRETRAINED_INIT_CONFIGURATION _UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _UpperCamelCase = ConvBertTokenizer def __init__( self , a__=None , a__=None , a__=True , a__="[UNK]" , a__="[SEP]" , a__="[PAD]" , a__="[CLS]" , a__="[MASK]" , a__=True , a__=None , **a__ , ): super().__init__( a__ , tokenizer_file=a__ , do_lower_case=a__ , unk_token=a__ , sep_token=a__ , pad_token=a__ , cls_token=a__ , mask_token=a__ , tokenize_chinese_chars=a__ , strip_accents=a__ , **a__ , ) _lowerCamelCase = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , a__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , a__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , a__ ) != tokenize_chinese_chars ): _lowerCamelCase = getattr(a__ , normalizer_state.pop('''type''' ) ) _lowerCamelCase = do_lower_case _lowerCamelCase = strip_accents _lowerCamelCase = tokenize_chinese_chars _lowerCamelCase = normalizer_class(**a__ ) _lowerCamelCase = do_lower_case def _UpperCAmelCase ( self , a__ , a__=None ): _lowerCamelCase = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _UpperCAmelCase ( self , a__ , a__ = None ): _lowerCamelCase = [self.sep_token_id] _lowerCamelCase = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase ( self , a__ , a__ = None ): _lowerCamelCase = self._tokenizer.model.save(a__ , name=a__ ) return tuple(a__ )
297
from __future__ import annotations from typing import Any def _lowerCamelCase ( _a ): """simple docstring""" if not postfix_notation: return 0 _lowerCamelCase = {'''+''', '''-''', '''*''', '''/'''} _lowerCamelCase = [] for token in postfix_notation: if token in operations: _lowerCamelCase , _lowerCamelCase = stack.pop(), stack.pop() if token == "+": stack.append(a + b ) elif token == "-": stack.append(a - b ) elif token == "*": stack.append(a * b ) else: if a * b < 0 and a % b != 0: stack.append(a // b + 1 ) else: stack.append(a // b ) else: stack.append(int(_a ) ) return stack.pop() if __name__ == "__main__": import doctest doctest.testmod()
297
1
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : int = logging.get_logger(__name__) a : Any = '▁' a : Dict = {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'} a : Tuple = { 'vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model', }, 'monolingual_vocab_file': { 'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt', }, } a : Optional[int] = {'vinai/bartpho-syllable': 1_024} class _a ( UpperCAmelCase_ ): A = VOCAB_FILES_NAMES A = PRETRAINED_VOCAB_FILES_MAP A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A = ['input_ids', 'attention_mask'] def __init__(self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="</s>", SCREAMING_SNAKE_CASE_="<s>", SCREAMING_SNAKE_CASE_="<unk>", SCREAMING_SNAKE_CASE_="<pad>", SCREAMING_SNAKE_CASE_="<mask>", SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> None: UpperCAmelCase_: Any = AddedToken(__UpperCAmelCase, lstrip=__UpperCAmelCase, rstrip=__UpperCAmelCase ) if isinstance(__UpperCAmelCase, __UpperCAmelCase ) else mask_token UpperCAmelCase_: Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__UpperCAmelCase, eos_token=__UpperCAmelCase, unk_token=__UpperCAmelCase, sep_token=__UpperCAmelCase, cls_token=__UpperCAmelCase, pad_token=__UpperCAmelCase, mask_token=__UpperCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **__UpperCAmelCase, ) UpperCAmelCase_: List[str] = vocab_file UpperCAmelCase_: Dict = monolingual_vocab_file UpperCAmelCase_: int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__UpperCAmelCase ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility UpperCAmelCase_: List[Any] = {} UpperCAmelCase_: int = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(__UpperCAmelCase ) not in self.fairseq_tokens_to_ids: UpperCAmelCase_: Any = cnt cnt += 1 with open(__UpperCAmelCase, """r""", encoding="""utf-8""" ) as f: for line in f.readlines(): UpperCAmelCase_: Optional[int] = line.strip().split()[0] UpperCAmelCase_: Union[str, Any] = len(self.fairseq_tokens_to_ids ) if str(__UpperCAmelCase ) not in self.fairseq_tokens_to_ids: UpperCAmelCase_: int = len(self.fairseq_tokens_to_ids ) UpperCAmelCase_: List[str] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__(self ) -> List[Any]: UpperCAmelCase_: int = self.__dict__.copy() UpperCAmelCase_: Tuple = None UpperCAmelCase_: List[str] = self.sp_model.serialized_model_proto() return state def __setstate__(self, SCREAMING_SNAKE_CASE_ ) -> Union[str, Any]: UpperCAmelCase_: Dict = d # for backward compatibility if not hasattr(self, """sp_model_kwargs""" ): UpperCAmelCase_: str = {} UpperCAmelCase_: Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_: Tuple = [self.cls_token_id] UpperCAmelCase_: Any = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None, SCREAMING_SNAKE_CASE_ = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase, token_ids_a=__UpperCAmelCase, already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] + ([0] * len(__UpperCAmelCase )) + [1] def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> List[int]: UpperCAmelCase_: Dict = [self.sep_token_id] UpperCAmelCase_: 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 + sep + token_ids_a + sep ) * [0] @property def __snake_case (self ) -> Any: return len(self.fairseq_ids_to_tokens ) def __snake_case (self ) -> Any: UpperCAmelCase_: Optional[int] = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> List[str]: return self.sp_model.encode(__UpperCAmelCase, out_type=__UpperCAmelCase ) def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> List[Any]: if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> Tuple: return self.fairseq_ids_to_tokens[index] def __snake_case (self, SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCAmelCase_: Tuple = """""".join(__UpperCAmelCase ).replace(__UpperCAmelCase, """ """ ).strip() return out_string def __snake_case (self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(f'Vocabulary path ({save_directory}) should be a directory' ) return UpperCAmelCase_: Optional[Any] = os.path.join( __UpperCAmelCase, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) UpperCAmelCase_: Optional[Any] = os.path.join( __UpperCAmelCase, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_vocab_file"""], ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, __UpperCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCAmelCase, """wb""" ) as fi: UpperCAmelCase_: Optional[int] = self.sp_model.serialized_model_proto() fi.write(__UpperCAmelCase ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( __UpperCAmelCase ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file, __UpperCAmelCase ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(__UpperCAmelCase, """w""", encoding="""utf-8""" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'{str(__UpperCAmelCase )} \n' ) return out_vocab_file, out_monolingual_vocab_file
556
import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class A ( unittest.TestCase ): def lowercase_ (self : Any , __UpperCAmelCase : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase__ = 3 UpperCAmelCase__ = 2_5_0 UpperCAmelCase__ = ids_tensor((batch_size, length) , __UpperCAmelCase ) UpperCAmelCase__ = torch.ones((batch_size, length) , device=__UpperCAmelCase , dtype=torch.float ) / length return input_ids, scores def lowercase_ (self : int ) -> int: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(5 ) UpperCAmelCase__ = StoppingCriteriaList( [ MaxLengthCriteria(max_length=1_0 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(1_0 ) self.assertTrue(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) def lowercase_ (self : Dict ) -> List[Any]: """simple docstring""" UpperCAmelCase__ = MaxLengthCriteria(max_length=1_0 ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(5 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(1_0 ) self.assertTrue(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) def lowercase_ (self : List[str] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(5 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(9 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(1_0 ) self.assertTrue(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 1_0 ) def lowercase_ (self : List[Any] ) -> List[str]: """simple docstring""" UpperCAmelCase__ , UpperCAmelCase__ = self._get_tensors(5 ) UpperCAmelCase__ = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) UpperCAmelCase__ = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(__UpperCAmelCase , __UpperCAmelCase ) ) def lowercase_ (self : Union[str, Any] ) -> Optional[int]: """simple docstring""" validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 ) with self.assertWarns(__UpperCAmelCase ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 ) UpperCAmelCase__ = validate_stopping_criteria(StoppingCriteriaList() , 1_1 ) self.assertEqual(len(__UpperCAmelCase ) , 1 )
486
0
from maths.prime_check import is_prime def UpperCamelCase ( __lowercase : int ): '''simple docstring''' if not isinstance(__lowercase ,__lowercase ): A_ : List[Any] = f'''Input value of [number={number}] must be an integer''' raise TypeError(__lowercase ) if is_prime(__lowercase ) and is_prime(number + 2 ): return number + 2 else: return -1 if __name__ == "__main__": import doctest doctest.testmod()
70
import random def UpperCamelCase ( __lowercase : int ): '''simple docstring''' A_ : Tuple = num - 1 A_ : Optional[Any] = 0 while s % 2 == 0: A_ : Optional[int] = s // 2 t += 1 for _ in range(5 ): A_ : Optional[int] = random.randrange(2 ,num - 1 ) A_ : Any = pow(__lowercase ,__lowercase ,__lowercase ) if v != 1: A_ : List[str] = 0 while v != (num - 1): if i == t - 1: return False else: A_ : Union[str, Any] = i + 1 A_ : Tuple = (v**2) % num return True def UpperCamelCase ( __lowercase : int ): '''simple docstring''' if num < 2: return False A_ : Optional[Any] = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 1_01, 1_03, 1_07, 1_09, 1_13, 1_27, 1_31, 1_37, 1_39, 1_49, 1_51, 1_57, 1_63, 1_67, 1_73, 1_79, 1_81, 1_91, 1_93, 1_97, 1_99, 2_11, 2_23, 2_27, 2_29, 2_33, 2_39, 2_41, 2_51, 2_57, 2_63, 2_69, 2_71, 2_77, 2_81, 2_83, 2_93, 3_07, 3_11, 3_13, 3_17, 3_31, 3_37, 3_47, 3_49, 3_53, 3_59, 3_67, 3_73, 3_79, 3_83, 3_89, 3_97, 4_01, 4_09, 4_19, 4_21, 4_31, 4_33, 4_39, 4_43, 4_49, 4_57, 4_61, 4_63, 4_67, 4_79, 4_87, 4_91, 4_99, 5_03, 5_09, 5_21, 5_23, 5_41, 5_47, 5_57, 5_63, 5_69, 5_71, 5_77, 5_87, 5_93, 5_99, 6_01, 6_07, 6_13, 6_17, 6_19, 6_31, 6_41, 6_43, 6_47, 6_53, 6_59, 6_61, 6_73, 6_77, 6_83, 6_91, 7_01, 7_09, 7_19, 7_27, 7_33, 7_39, 7_43, 7_51, 7_57, 7_61, 7_69, 7_73, 7_87, 7_97, 8_09, 8_11, 8_21, 8_23, 8_27, 8_29, 8_39, 8_53, 8_57, 8_59, 8_63, 8_77, 8_81, 8_83, 8_87, 9_07, 9_11, 9_19, 9_29, 9_37, 9_41, 9_47, 9_53, 9_67, 9_71, 9_77, 9_83, 9_91, 9_97, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(__lowercase ) def UpperCamelCase ( __lowercase : int = 10_24 ): '''simple docstring''' while True: A_ : Union[str, Any] = random.randrange(2 ** (keysize - 1) ,2 ** (keysize) ) if is_prime_low_num(__lowercase ): return num if __name__ == "__main__": _UpperCAmelCase = generate_large_prime() print(("""Prime number:""", num)) print(("""is_prime_low_num:""", is_prime_low_num(num)))
70
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer _lowerCAmelCase : Dict =logging.get_logger(__name__) _lowerCAmelCase : Union[str, Any] ={"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} _lowerCAmelCase : Tuple ={ """vocab_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt""" ), """google/realm-orqa-nq-openqa""": """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-nq-reader""": """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt""", """google/realm-orqa-wq-openqa""": """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt""", """google/realm-orqa-wq-reader""": """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt""", }, """tokenizer_file""": { """google/realm-cc-news-pretrained-embedder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont""" ), """google/realm-cc-news-pretrained-encoder""": ( """https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-scorer""": ( """https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json""" ), """google/realm-cc-news-pretrained-openqa""": ( """https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json""" ), """google/realm-orqa-nq-openqa""": ( """https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-nq-reader""": ( """https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-openqa""": ( """https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json""" ), """google/realm-orqa-wq-reader""": ( """https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json""" ), }, } _lowerCAmelCase : int ={ """google/realm-cc-news-pretrained-embedder""": 5_12, """google/realm-cc-news-pretrained-encoder""": 5_12, """google/realm-cc-news-pretrained-scorer""": 5_12, """google/realm-cc-news-pretrained-openqa""": 5_12, """google/realm-orqa-nq-openqa""": 5_12, """google/realm-orqa-nq-reader""": 5_12, """google/realm-orqa-wq-openqa""": 5_12, """google/realm-orqa-wq-reader""": 5_12, } _lowerCAmelCase : str ={ """google/realm-cc-news-pretrained-embedder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-encoder""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-scorer""": {"""do_lower_case""": True}, """google/realm-cc-news-pretrained-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-nq-reader""": {"""do_lower_case""": True}, """google/realm-orqa-wq-openqa""": {"""do_lower_case""": True}, """google/realm-orqa-wq-reader""": {"""do_lower_case""": True}, } class __UpperCamelCase ( A__ ): '''simple docstring''' __magic_name__ = VOCAB_FILES_NAMES __magic_name__ = PRETRAINED_VOCAB_FILES_MAP __magic_name__ = PRETRAINED_INIT_CONFIGURATION __magic_name__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __magic_name__ = RealmTokenizer def __init__( self , lowerCamelCase__=None , lowerCamelCase__=None , lowerCamelCase__=True , lowerCamelCase__="[UNK]" , lowerCamelCase__="[SEP]" , lowerCamelCase__="[PAD]" , lowerCamelCase__="[CLS]" , lowerCamelCase__="[MASK]" , lowerCamelCase__=True , lowerCamelCase__=None , **lowerCamelCase__ , ): super().__init__( lowerCamelCase__ , tokenizer_file=lowerCamelCase__ , do_lower_case=lowerCamelCase__ , unk_token=lowerCamelCase__ , sep_token=lowerCamelCase__ , pad_token=lowerCamelCase__ , cls_token=lowerCamelCase__ , mask_token=lowerCamelCase__ , tokenize_chinese_chars=lowerCamelCase__ , strip_accents=lowerCamelCase__ , **lowerCamelCase__ , ) UpperCAmelCase__: Any = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , lowerCamelCase__ ) != do_lower_case or normalizer_state.get("strip_accents" , lowerCamelCase__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , lowerCamelCase__ ) != tokenize_chinese_chars ): UpperCAmelCase__: Union[str, Any] = getattr(lowerCamelCase__ , normalizer_state.pop("type" ) ) UpperCAmelCase__: Dict = do_lower_case UpperCAmelCase__: Optional[int] = strip_accents UpperCAmelCase__: Any = tokenize_chinese_chars UpperCAmelCase__: str = normalizer_class(**lowerCamelCase__ ) UpperCAmelCase__: Union[str, Any] = do_lower_case def _UpperCAmelCase ( self , lowerCamelCase__ , **lowerCamelCase__ ): UpperCAmelCase__: Dict = PaddingStrategy.MAX_LENGTH UpperCAmelCase__: Tuple = text UpperCAmelCase__: int = kwargs.pop("text_pair" , lowerCamelCase__ ) UpperCAmelCase__: Optional[Any] = kwargs.pop("return_tensors" , lowerCamelCase__ ) UpperCAmelCase__: str = { '''input_ids''': [], '''attention_mask''': [], '''token_type_ids''': [], } for idx, candidate_text in enumerate(lowerCamelCase__ ): if batch_text_pair is not None: UpperCAmelCase__: Tuple = batch_text_pair[idx] else: UpperCAmelCase__: Any = None UpperCAmelCase__: List[str] = super().__call__(lowerCamelCase__ , lowerCamelCase__ , return_tensors=lowerCamelCase__ , **lowerCamelCase__ ) UpperCAmelCase__: List[Any] = encoded_candidates.get("input_ids" ) UpperCAmelCase__: Tuple = encoded_candidates.get("attention_mask" ) UpperCAmelCase__: Dict = encoded_candidates.get("token_type_ids" ) if encoded_input_ids is not None: output_data["input_ids"].append(lowerCamelCase__ ) if encoded_attention_mask is not None: output_data["attention_mask"].append(lowerCamelCase__ ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(lowerCamelCase__ ) UpperCAmelCase__: Optional[Any] = {key: item for key, item in output_data.items() if len(lowerCamelCase__ ) != 0} return BatchEncoding(lowerCamelCase__ , tensor_type=lowerCamelCase__ ) def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=None ): UpperCAmelCase__: Optional[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 _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None ): UpperCAmelCase__: str = [self.sep_token_id] UpperCAmelCase__: Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__ = None ): UpperCAmelCase__: Any = self._tokenizer.model.save(lowerCamelCase__ , name=lowerCamelCase__ ) return tuple(lowerCamelCase__ )
113
"""simple docstring""" import os import sys import unittest __lowerCamelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __lowerCamelCase = os.path.join(git_repo_path, "src", "diffusers") class _snake_case ( unittest.TestCase ): '''simple docstring''' def snake_case_ ( self : Optional[int] ): UpperCAmelCase_ :Tuple = find_backend(''' if not is_torch_available():''' ) self.assertEqual(snake_case , '''torch''' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") UpperCAmelCase_ :List[str] = find_backend(''' if not (is_torch_available() and is_transformers_available()):''' ) self.assertEqual(snake_case , '''torch_and_transformers''' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") UpperCAmelCase_ :str = find_backend( ''' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''' ) self.assertEqual(snake_case , '''torch_and_transformers_and_onnx''' ) def snake_case_ ( self : List[str] ): UpperCAmelCase_ :Any = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , snake_case ) self.assertIn('''torch_and_transformers''' , snake_case ) self.assertIn('''flax_and_transformers''' , snake_case ) self.assertIn('''torch_and_transformers_and_onnx''' , snake_case ) # Likewise, we can't assert on the exact content of a key self.assertIn('''UNet2DModel''' , objects['''torch'''] ) self.assertIn('''FlaxUNet2DConditionModel''' , objects['''flax'''] ) self.assertIn('''StableDiffusionPipeline''' , objects['''torch_and_transformers'''] ) self.assertIn('''FlaxStableDiffusionPipeline''' , objects['''flax_and_transformers'''] ) self.assertIn('''LMSDiscreteScheduler''' , objects['''torch_and_scipy'''] ) self.assertIn('''OnnxStableDiffusionPipeline''' , objects['''torch_and_transformers_and_onnx'''] ) def snake_case_ ( self : Optional[int] ): UpperCAmelCase_ :List[Any] = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(snake_case , '''\nCONSTANT = None\n''' ) UpperCAmelCase_ :Tuple = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( snake_case , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) UpperCAmelCase_ :int = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, \'torch\') @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, \'torch\') ''' UpperCAmelCase_ :int = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(snake_case , snake_case ) def snake_case_ ( self : Any ): UpperCAmelCase_ :int = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, ["torch"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) ''' UpperCAmelCase_ :Optional[int] = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , snake_case )
608
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ....tokenization_utils_fast import PreTrainedTokenizerFast from ....utils import logging from .tokenization_retribert import RetriBertTokenizer a__ : str = logging.get_logger(__name__) a__ : Tuple = {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""} a__ : Dict = { """vocab_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/vocab.txt""" ), }, """tokenizer_file""": { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/tokenizer.json""" ), }, } a__ : List[str] = { """yjernite/retribert-base-uncased""": 5_1_2, } a__ : int = { """yjernite/retribert-base-uncased""": {"""do_lower_case""": True}, } class lowercase ( UpperCAmelCase_ ): """simple docstring""" snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = PRETRAINED_INIT_CONFIGURATION snake_case_ = RetriBertTokenizer snake_case_ = ['input_ids', 'attention_mask'] def __init__( self : Any , a_ : str=None , a_ : Any=None , a_ : Union[str, Any]=True , a_ : List[Any]="[UNK]" , a_ : Dict="[SEP]" , a_ : List[Any]="[PAD]" , a_ : str="[CLS]" , a_ : Optional[Any]="[MASK]" , a_ : List[Any]=True , a_ : Dict=None , **a_ : Optional[int] , ): """simple docstring""" super().__init__( a_ , tokenizer_file=a_ , do_lower_case=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , tokenize_chinese_chars=a_ , strip_accents=a_ , **a_ , ) lowerCamelCase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("""lowercase""" , a_ ) != do_lower_case or normalizer_state.get("""strip_accents""" , a_ ) != strip_accents or normalizer_state.get("""handle_chinese_chars""" , a_ ) != tokenize_chinese_chars ): lowerCamelCase__ = getattr(a_ , normalizer_state.pop("""type""" ) ) lowerCamelCase__ = do_lower_case lowerCamelCase__ = strip_accents lowerCamelCase__ = tokenize_chinese_chars lowerCamelCase__ = normalizer_class(**a_ ) lowerCamelCase__ = do_lower_case def _UpperCamelCase ( self : List[Any] , a_ : int , a_ : Any=None ): """simple docstring""" lowerCamelCase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _UpperCamelCase ( self : Dict , a_ : List[int] , a_ : Optional[List[int]] = None ): """simple docstring""" lowerCamelCase__ = [self.sep_token_id] lowerCamelCase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _UpperCamelCase ( self : Optional[Any] , a_ : str , a_ : Optional[str] = None ): """simple docstring""" lowerCamelCase__ = self._tokenizer.model.save(a_ , name=a_ ) return tuple(a_ )
712
import inspect import unittest from transformers import MobileViTConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileViTImageProcessor class lowercase ( UpperCAmelCase_ ): """simple docstring""" def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" lowerCamelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a_ , """hidden_sizes""" ) ) self.parent.assertTrue(hasattr(a_ , """neck_hidden_sizes""" ) ) self.parent.assertTrue(hasattr(a_ , """num_attention_heads""" ) ) class lowercase : """simple docstring""" def __init__( self : Optional[int] , a_ : Dict , a_ : Tuple=13 , a_ : Any=32 , a_ : Optional[int]=2 , a_ : Optional[int]=3 , a_ : List[Any]=6_40 , a_ : Optional[int]=4 , a_ : Dict="silu" , a_ : List[Any]=3 , a_ : Union[str, Any]=32 , a_ : Optional[int]=0.1 , a_ : Any=0.1 , a_ : List[str]=0.1 , a_ : str=0.0_2 , a_ : str=True , a_ : Optional[int]=True , a_ : List[Any]=10 , a_ : Tuple=None , ): """simple docstring""" lowerCamelCase__ = parent lowerCamelCase__ = batch_size lowerCamelCase__ = image_size lowerCamelCase__ = patch_size lowerCamelCase__ = num_channels lowerCamelCase__ = last_hidden_size lowerCamelCase__ = num_attention_heads lowerCamelCase__ = hidden_act lowerCamelCase__ = conv_kernel_size lowerCamelCase__ = output_stride lowerCamelCase__ = hidden_dropout_prob lowerCamelCase__ = attention_probs_dropout_prob lowerCamelCase__ = classifier_dropout_prob lowerCamelCase__ = use_labels lowerCamelCase__ = is_training lowerCamelCase__ = num_labels lowerCamelCase__ = initializer_range lowerCamelCase__ = scope def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" lowerCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ = None lowerCamelCase__ = None if self.use_labels: lowerCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) lowerCamelCase__ = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCamelCase__ = self.get_config() return config, pixel_values, labels, pixel_labels def _UpperCamelCase ( self : Any ): """simple docstring""" return MobileViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def _UpperCamelCase ( self : Tuple , a_ : Dict , a_ : Dict , a_ : Dict , a_ : str ): """simple docstring""" lowerCamelCase__ = MobileViTModel(config=a_ ) model.to(a_ ) model.eval() lowerCamelCase__ = model(a_ ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _UpperCamelCase ( self : str , a_ : Tuple , a_ : int , a_ : str , a_ : Tuple ): """simple docstring""" lowerCamelCase__ = self.num_labels lowerCamelCase__ = MobileViTForImageClassification(a_ ) model.to(a_ ) model.eval() lowerCamelCase__ = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _UpperCamelCase ( self : Optional[Any] , a_ : List[Any] , a_ : str , a_ : List[str] , a_ : int ): """simple docstring""" lowerCamelCase__ = self.num_labels lowerCamelCase__ = MobileViTForSemanticSegmentation(a_ ) model.to(a_ ) model.eval() lowerCamelCase__ = model(a_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) lowerCamelCase__ = model(a_ , labels=a_ ) self.parent.assertEqual( result.logits.shape , ( self.batch_size, self.num_labels, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def _UpperCamelCase ( self : Optional[int] ): """simple docstring""" lowerCamelCase__ = self.prepare_config_and_inputs() lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = config_and_inputs lowerCamelCase__ = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class lowercase ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): """simple docstring""" snake_case_ = ( (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation) if is_torch_available() else () ) snake_case_ = ( { 'feature-extraction': MobileViTModel, 'image-classification': MobileViTForImageClassification, 'image-segmentation': MobileViTForSemanticSegmentation, } if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def _UpperCamelCase ( self : Tuple ): """simple docstring""" lowerCamelCase__ = MobileViTModelTester(self ) lowerCamelCase__ = MobileViTConfigTester(self , config_class=a_ , has_text_modality=a_ ) def _UpperCamelCase ( self : List[str] ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason="""MobileViT does not use inputs_embeds""" ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" pass @unittest.skip(reason="""MobileViT does not support input and output embeddings""" ) def _UpperCamelCase ( self : Union[str, Any] ): """simple docstring""" pass @unittest.skip(reason="""MobileViT does not output attentions""" ) def _UpperCamelCase ( self : str ): """simple docstring""" pass def _UpperCamelCase ( self : Optional[Any] ): """simple docstring""" lowerCamelCase__ , lowerCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ = model_class(a_ ) lowerCamelCase__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ = [*signature.parameters.keys()] lowerCamelCase__ = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a_ ) @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""" ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" pass def _UpperCamelCase ( self : Any ): """simple docstring""" lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" def check_hidden_states_output(a_ : Any , a_ : List[str] , a_ : str ): lowerCamelCase__ = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): lowerCamelCase__ = model(**self._prepare_for_class(a_ , a_ ) ) lowerCamelCase__ = outputs.hidden_states lowerCamelCase__ = 5 self.assertEqual(len(a_ ) , a_ ) # MobileViT's feature maps are of shape (batch_size, num_channels, height, width) # with the width and height being successively divided by 2. lowerCamelCase__ = 2 for i in range(len(a_ ) ): self.assertListEqual( list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , ) divisor *= 2 self.assertEqual(self.model_tester.output_stride , divisor // 2 ) lowerCamelCase__ , lowerCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCamelCase__ = True check_hidden_states_output(a_ , a_ , a_ ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def _UpperCamelCase ( self : List[Any] ): """simple docstring""" lowerCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a_ ) @slow def _UpperCamelCase ( self : List[Any] ): """simple docstring""" for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ = MobileViTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def snake_case (): '''simple docstring''' lowerCamelCase__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): """simple docstring""" @cached_property def _UpperCamelCase ( self : Optional[int] ): """simple docstring""" return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""" ) if is_vision_available() else None @slow def _UpperCamelCase ( self : List[str] ): """simple docstring""" lowerCamelCase__ = MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""" ).to(a_ ) lowerCamelCase__ = self.default_image_processor lowerCamelCase__ = prepare_img() lowerCamelCase__ = image_processor(images=a_ , return_tensors="""pt""" ).to(a_ ) # forward pass with torch.no_grad(): lowerCamelCase__ = model(**a_ ) # verify the logits lowerCamelCase__ = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , a_ ) lowerCamelCase__ = torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[str] ): """simple docstring""" lowerCamelCase__ = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase__ = model.to(a_ ) lowerCamelCase__ = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase__ = prepare_img() lowerCamelCase__ = image_processor(images=a_ , return_tensors="""pt""" ).to(a_ ) # forward pass with torch.no_grad(): lowerCamelCase__ = model(**a_ ) lowerCamelCase__ = outputs.logits # verify the logits lowerCamelCase__ = torch.Size((1, 21, 32, 32) ) self.assertEqual(logits.shape , a_ ) lowerCamelCase__ = torch.tensor( [ [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]], [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]], [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]], ] , device=a_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , a_ , atol=1e-4 ) ) @slow def _UpperCamelCase ( self : List[str] ): """simple docstring""" lowerCamelCase__ = MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase__ = model.to(a_ ) lowerCamelCase__ = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""" ) lowerCamelCase__ = prepare_img() lowerCamelCase__ = image_processor(images=a_ , return_tensors="""pt""" ).to(a_ ) # forward pass with torch.no_grad(): lowerCamelCase__ = model(**a_ ) lowerCamelCase__ = outputs.logits.detach().cpu() lowerCamelCase__ = image_processor.post_process_semantic_segmentation(outputs=a_ , target_sizes=[(50, 60)] ) lowerCamelCase__ = torch.Size((50, 60) ) self.assertEqual(segmentation[0].shape , a_ ) lowerCamelCase__ = image_processor.post_process_semantic_segmentation(outputs=a_ ) lowerCamelCase__ = torch.Size((32, 32) ) self.assertEqual(segmentation[0].shape , a_ )
235
0
from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets UpperCamelCase = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" UpperCamelCase = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" UpperCamelCase = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> int: return float((preds == labels).mean() ) def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]: _lowercase : Optional[int] = simple_accuracy(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) _lowercase : int = float(fa_score(y_true=SCREAMING_SNAKE_CASE , y_pred=SCREAMING_SNAKE_CASE ) ) return { "accuracy": acc, "f1": fa, } def __magic_name__ ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Any: _lowercase : Optional[Any] = float(pearsonr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] ) _lowercase : int = float(spearmanr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase_ ( datasets.Metric ): def __a ( self ): if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), 'references': datasets.Value('int64' if self.config_name != 'stsb' else 'float32' ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' , ) def __a ( self , _lowerCAmelCase , _lowerCAmelCase ): if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(_lowerCAmelCase , _lowerCAmelCase )} elif self.config_name == "stsb": return pearson_and_spearman(_lowerCAmelCase , _lowerCAmelCase ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(_lowerCAmelCase , _lowerCAmelCase ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(_lowerCAmelCase , _lowerCAmelCase )} else: raise KeyError( 'You should supply a configuration name selected in ' '["sst2", "mnli", "mnli_mismatched", "mnli_matched", ' '"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]' )
66
from __future__ import annotations def SCREAMING_SNAKE_CASE_ ( _snake_case :dict , _snake_case :str ) -> set[str]: _A , _A = set(_snake_case ), [start] while stack: _A = stack.pop() explored.add(_snake_case ) # Differences from BFS: # 1) pop last element instead of first one # 2) add adjacent elements to stack without exploring them for adj in reversed(graph[v] ): if adj not in explored: stack.append(_snake_case ) return explored UpperCAmelCase_ = { """A""": ["""B""", """C""", """D"""], """B""": ["""A""", """D""", """E"""], """C""": ["""A""", """F"""], """D""": ["""B""", """D"""], """E""": ["""B""", """F"""], """F""": ["""C""", """E""", """G"""], """G""": ["""F"""], } if __name__ == "__main__": import doctest doctest.testmod() print(depth_first_search(G, """A"""))
2
0
import inspect import unittest from transformers import MobileNetVaConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MobileNetVaForImageClassification, MobileNetVaModel from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import MobileNetVaImageProcessor class lowercase ( a ): def __snake_case( self : Dict ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_UpperCAmelCase , "tf_padding" ) ) self.parent.assertTrue(hasattr(_UpperCAmelCase , "depth_multiplier" ) ) class lowercase : def __init__( self : Optional[int] , _UpperCamelCase : List[str] , _UpperCamelCase : int=13 , _UpperCamelCase : List[Any]=3 , _UpperCamelCase : str=32 , _UpperCamelCase : Any=0.2_5 , _UpperCamelCase : Union[str, Any]=8 , _UpperCamelCase : Dict=True , _UpperCamelCase : Optional[int]=1_024 , _UpperCamelCase : Optional[Any]=32 , _UpperCamelCase : int="relu6" , _UpperCamelCase : int=0.1 , _UpperCamelCase : Union[str, Any]=0.0_2 , _UpperCamelCase : int=True , _UpperCamelCase : Optional[Any]=True , _UpperCamelCase : Optional[Any]=10 , _UpperCamelCase : Tuple=None , ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = num_channels SCREAMING_SNAKE_CASE = image_size SCREAMING_SNAKE_CASE = depth_multiplier SCREAMING_SNAKE_CASE = min_depth SCREAMING_SNAKE_CASE = tf_padding SCREAMING_SNAKE_CASE = int(last_hidden_size * depth_multiplier ) SCREAMING_SNAKE_CASE = output_stride SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = classifier_dropout_prob SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = num_labels SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = scope def __snake_case( self : Any ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE = self.get_config() return config, pixel_values, labels, pixel_labels def __snake_case( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return MobileNetVaConfig( num_channels=self.num_channels , image_size=self.image_size , depth_multiplier=self.depth_multiplier , min_depth=self.min_depth , tf_padding=self.tf_padding , hidden_act=self.hidden_act , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , ) def __snake_case( self : List[str] , _UpperCamelCase : Tuple , _UpperCamelCase : List[Any] , _UpperCamelCase : List[Any] , _UpperCamelCase : List[str] ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileNetVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE = model(_UpperCAmelCase ) self.parent.assertEqual( result.last_hidden_state.shape , ( self.batch_size, self.last_hidden_size, self.image_size // self.output_stride, self.image_size // self.output_stride, ) , ) def __snake_case( self : str , _UpperCamelCase : Tuple , _UpperCamelCase : Any , _UpperCamelCase : str , _UpperCamelCase : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.num_labels SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() SCREAMING_SNAKE_CASE = model(_UpperCAmelCase , labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __snake_case( self : List[str] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = config_and_inputs SCREAMING_SNAKE_CASE = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class lowercase ( a , a , unittest.TestCase ): lowercase__ : Dict = (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else () lowercase__ : Union[str, Any] = ( {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification} if is_torch_available() else {} ) lowercase__ : Any = False lowercase__ : List[Any] = False lowercase__ : Tuple = False lowercase__ : str = False def __snake_case( self : Optional[Any] ) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileNetVaModelTester(self ) SCREAMING_SNAKE_CASE = MobileNetVaConfigTester(self , config_class=_UpperCAmelCase , has_text_modality=_UpperCAmelCase ) def __snake_case( self : List[Any] ) -> Any: '''simple docstring''' self.config_tester.run_common_tests() @unittest.skip(reason="MobileNetV1 does not use inputs_embeds" ) def __snake_case( self : int ) -> str: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not support input and output embeddings" ) def __snake_case( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' pass @unittest.skip(reason="MobileNetV1 does not output attentions" ) def __snake_case( self : str ) -> List[str]: '''simple docstring''' pass def __snake_case( self : Dict ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = model_class(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE = ["pixel_values"] self.assertListEqual(arg_names[:1] , _UpperCAmelCase ) def __snake_case( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __snake_case( self : str ) -> Optional[int]: '''simple docstring''' def check_hidden_states_output(_UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[int] , _UpperCamelCase : int ): SCREAMING_SNAKE_CASE = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**self._prepare_for_class(_UpperCAmelCase , _UpperCAmelCase ) ) SCREAMING_SNAKE_CASE = outputs.hidden_states SCREAMING_SNAKE_CASE = 26 self.assertEqual(len(_UpperCAmelCase ) , _UpperCAmelCase ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE = True check_hidden_states_output(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) def __snake_case( self : List[Any] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __snake_case( self : List[Any] ) -> Optional[int]: '''simple docstring''' for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE = MobileNetVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase (): SCREAMING_SNAKE_CASE = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class lowercase ( unittest.TestCase ): @cached_property def __snake_case( self : Tuple ) -> Tuple: '''simple docstring''' return ( MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224" ) if is_vision_available() else None ) @slow def __snake_case( self : Optional[Any] ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224" ).to(_UpperCAmelCase ) SCREAMING_SNAKE_CASE = self.default_image_processor SCREAMING_SNAKE_CASE = prepare_img() SCREAMING_SNAKE_CASE = image_processor(images=_UpperCAmelCase , return_tensors="pt" ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE = model(**_UpperCAmelCase ) # verify the logits SCREAMING_SNAKE_CASE = torch.Size((1, 1_001) ) self.assertEqual(outputs.logits.shape , _UpperCAmelCase ) SCREAMING_SNAKE_CASE = torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _UpperCAmelCase , atol=1e-4 ) )
714
from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) def __lowerCamelCase (UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any] ): return [ int(1_0_0_0 * (box[0] / width) ), int(1_0_0_0 * (box[1] / height) ), int(1_0_0_0 * (box[2] / width) ), int(1_0_0_0 * (box[3] / height) ), ] def __lowerCamelCase (UpperCAmelCase__ : np.ndarray , UpperCAmelCase__ : Optional[str] , UpperCAmelCase__ : Optional[str] = None ): SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else "" # apply OCR SCREAMING_SNAKE_CASE = to_pil_image(UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = pil_image.size SCREAMING_SNAKE_CASE = pytesseract.image_to_data(UpperCAmelCase__ , lang=UpperCAmelCase__ , output_type="dict" , config=UpperCAmelCase__ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = data["text"], data["left"], data["top"], data["width"], data["height"] # filter empty words and corresponding coordinates SCREAMING_SNAKE_CASE = [idx for idx, word in enumerate(UpperCAmelCase__ ) if not word.strip()] SCREAMING_SNAKE_CASE = [word for idx, word in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] SCREAMING_SNAKE_CASE = [coord for idx, coord in enumerate(UpperCAmelCase__ ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format SCREAMING_SNAKE_CASE = [] for x, y, w, h in zip(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ): SCREAMING_SNAKE_CASE = [x, y, x + w, y + h] actual_boxes.append(UpperCAmelCase__ ) # finally, normalize the bounding boxes SCREAMING_SNAKE_CASE = [] for box in actual_boxes: normalized_boxes.append(normalize_box(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) ) assert len(UpperCAmelCase__ ) == len(UpperCAmelCase__ ), "Not as many words as there are bounding boxes" return words, normalized_boxes class lowercase ( a ): lowercase__ : Optional[int] = ["""pixel_values"""] def __init__( self : int , _UpperCamelCase : bool = True , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : bool = True , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = "" , **_UpperCamelCase : Optional[int] , ) -> None: '''simple docstring''' super().__init__(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = size if size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = do_resize SCREAMING_SNAKE_CASE = size SCREAMING_SNAKE_CASE = resample SCREAMING_SNAKE_CASE = apply_ocr SCREAMING_SNAKE_CASE = ocr_lang SCREAMING_SNAKE_CASE = tesseract_config def __snake_case( self : List[Any] , _UpperCamelCase : np.ndarray , _UpperCamelCase : Dict[str, int] , _UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , _UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCamelCase : Any , ) -> np.ndarray: '''simple docstring''' SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}" ) SCREAMING_SNAKE_CASE = (size["height"], size["width"]) return resize(_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase , data_format=_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : Tuple , _UpperCamelCase : ImageInput , _UpperCamelCase : bool = None , _UpperCamelCase : Dict[str, int] = None , _UpperCamelCase : PILImageResampling = None , _UpperCamelCase : bool = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[str] = None , _UpperCamelCase : Optional[Union[str, TensorType]] = None , _UpperCamelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCamelCase : str , ) -> PIL.Image.Image: '''simple docstring''' SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE = size if size is not None else self.size SCREAMING_SNAKE_CASE = get_size_dict(_UpperCamelCase ) SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE = apply_ocr if apply_ocr is not None else self.apply_ocr SCREAMING_SNAKE_CASE = ocr_lang if ocr_lang is not None else self.ocr_lang SCREAMING_SNAKE_CASE = tesseract_config if tesseract_config is not None else self.tesseract_config SCREAMING_SNAKE_CASE = make_list_of_images(_UpperCamelCase ) if not valid_images(_UpperCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE = [to_numpy_array(_UpperCamelCase ) for image in images] if apply_ocr: requires_backends(self , "pytesseract" ) SCREAMING_SNAKE_CASE = [] SCREAMING_SNAKE_CASE = [] for image in images: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = apply_tesseract(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) words_batch.append(_UpperCamelCase ) boxes_batch.append(_UpperCamelCase ) if do_resize: SCREAMING_SNAKE_CASE = [self.resize(image=_UpperCamelCase , size=_UpperCamelCase , resample=_UpperCamelCase ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) SCREAMING_SNAKE_CASE = [flip_channel_order(_UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = [to_channel_dimension_format(_UpperCamelCase , _UpperCamelCase ) for image in images] SCREAMING_SNAKE_CASE = BatchFeature(data={"pixel_values": images} , tensor_type=_UpperCamelCase ) if apply_ocr: SCREAMING_SNAKE_CASE = words_batch SCREAMING_SNAKE_CASE = boxes_batch return data
647
0